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.
1 2 3 4 5 6 7 8 9 10 |
$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 var_dump($key); |
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:
1 |
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.
1 2 |
$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.