Skip to content
Home » Web » PHP » How PHP Get Last Key of Array

How PHP Get Last Key of Array

There is no direct way or function for retrieving the last key of an array, but we can work around it.

end() + key()

First of all, we should set the pointer to the last element, then retrieve the key out of it. Please see the following example.

1  <?php
2  $arr = array("fruit" => "apple", "drink" => "coffee", "dessert" => "cake");
3  end($arr);
4  echo key($arr);
5  ?>

In the above, we use end() to make the pointer point to the last element in line 3, and then use key() to retrieve the last key in line 4.


In case you want to use the array in proper orders later in the codes, you can use reset() to force the pointer go back to the first element.

Leave a Reply

Your email address will not be published. Required fields are marked *