Get last key from array in PHP

The fastest and the correct way to get the last key from an array is:

$lastkey = array_pop(array_keys($arr));

Example:

$arr[] = array("red" => "apple", "yellow" => "banana");

Let’s say you want to add another element to the previous created array, for that you need to know the last created index so:

$lastkey = array_pop(array_keys($arr));
$arr[$lastkey]["brown"] = "kiwi";

And there you have it.

Leave a Comment

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>