I have a standard associative array in PHP. what's the simplest way to get the last key in that array?
example:
$foo = array('key1' => 'val1', 'key2' => 'val2', 'key3' => 'val3');
and i would like to get 'key3';
I have a standard associative array in PHP. what's the simplest way to get the last key in that array?
example:
$foo = array('key1' => 'val1', 'key2' => 'val2', 'key3' => 'val3');
and i would like to get 'key3';
$keys = array_keys($foo);
$last = end($keys);
you need to pass an actual variable to end
, you can't put another function inside there.
Fastest method would be this:
end($foo);
$last = key($foo);
Tesserex's method is unnecessarily resource hungry when you don't need all keys.
The following is not the simplest, but it will may be much happier to deal with large (in terms of number of elements; though will probably† be better for most uses) arrays than the other answers.
$last_key = key(array_slice($subject, -1, 1, true));
† educated guess, may not be true for all cases