How to get last key in an array in PHP
How to get last key in an array in PHP?
Arrays can have lots of elements, some that may not be needed at one point. Let’s say that we need in some cases the last key or last element of an array in PHP, what would you do?
A very good solution and clever practice would be the following one:
1st solution (clever)
You would use the end() function to move the pointer directly at the bottom of the array. That way you can have access directly to the last element.
$myArr = array(
'first' => 'first element',
'second' => 'second element',
'last' => 'third element',
end($myArr); // move the internal pointer to the end of the array
$key = key($myArr); // fetches the key of the element pointed to by the internal pointer
end()advances array ‘s internal pointer to the last element, and returns its value.
key()returns the index element of the current array position.
The above example will output:
string 'last' (length=4)
2nd solution (faster)
This would also work and is bit more faster. We are using array_slice() function for getting only the last element of the array.
$last_key = key( array_slice( $myArr, -1, 1, TRUE ) );
echo $last_key; //output "last"
Both solutions are good and can be used with confidence in your own projects.