Skip to content

How to Get The Last Key of an Array

There is no direct way or function for retrieving the last key of an array. But you can work around it. First of all, you 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.