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';
You can use the end() function in PHP to get the last element of any PHP array. It will set the internal pointer to the last element of the array and return its value.
The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.
The end() function moves the internal pointer to, and outputs, the last element in the array. Related methods: current() - returns the value of the current element in an array.
The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.
Fastest method would be this:
end($foo);
$last = key($foo);
Tesserex's method is unnecessarily resource hungry when you don't need all keys.
$keys = array_keys($foo);
$last = end($keys);
you need to pass an actual variable to end
, you can't put another function inside there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With