How can I get the last key of an array?
The end() function is an inbuilt function in PHP and is used to find the last element of the given array. The end() function changes the internal pointer of an array to point to the last element and returns the value of the last element.
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.
To get the first and last elements of an array, access the array at index 0 and the last index. For example, arr[0] returns the first element, whereas arr[arr. length - 1] returns the last element of the 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. Specified array.
A solution would be to use a combination of end
and key
(quoting) :
end()
advances array 's internal pointer to the last element, and returns its value. key()
returns the index element of the current array position. So, a portion of code such as this one should do the trick :
$array = array( 'first' => 123, 'second' => 456, 'last' => 789, ); end($array); // move the internal pointer to the end of the array $key = key($array); // fetches the key of the element pointed to by the internal pointer var_dump($key);
Will output :
string 'last' (length=4)
i.e. the key of the last element of my array.
After this has been done the array's internal pointer will be at the end of the array. As pointed out in the comments, you may want to run reset()
on the array to bring the pointer back to the beginning of the array.
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