Get final array key in PHP

I have a standard associative array in PHP. what's the easiest way to get the last key in this array?

Example:

$foo = array('key1' => 'val1', 'key2' => 'val2', 'key3' => 'val3');

and I would like to get "key3";

+5
source share
3 answers

The fastest way:

end($foo);
$last = key($foo);

The Tesserex method is unnecessarily resource-intensive when you do not need all the keys.

+9
source
$keys = array_keys($foo);
$last = end($keys);

you need to pass a valid variable to end, you cannot put another function there.

+8
source

, << → ( ; , , ), .

$last_key = key(array_slice($subject, -1, 1, true));

,

+1

All Articles