How to get last key in an array? How to get last key in an array? arrays arrays

How to get last key in an array?


A solution would be to use a combination of end and key (quoting) :

  • end() advances array 's internal pointer to the last element, and returns its value.
  • key() returns the index element of the current array position.

So, a portion of code such as this one should do the trick :

$array = array(    'first' => 123,    'second' => 456,    'last' => 789, );end($array);         // move the internal pointer to the end of the array$key = key($array);  // fetches the key of the element pointed to by the internal pointervar_dump($key);

Will output :

string 'last' (length=4)

i.e. the key of the last element of my array.

After this has been done the array's internal pointer will be at the end of the array. As pointed out in the comments, you may want to run reset() on the array to bring the pointer back to the beginning of the array.


Although end() seems to be the easiest, it's not the fastest. The faster, and much stronger alternative is array_slice():

$lastKey = key(array_slice($array, -1, 1, true));

As the tests say, on an array with 500000 elements, it is almost 7x faster!


Since PHP 7.3 (2018) there is (finally) function for this:http://php.net/manual/en/function.array-key-last.php

$array = ['apple'=>10,'grape'=>15,'orange'=>20];echo array_key_last ( $array )

will output

orange