Get last key-value pair in PHP array
I have an array that is structured like this:
[33] => Array
(
[time] => 1285571561
[user] => test0
)
[34] => Array
(
[time] => 1285571659
[user] => test1
)
[35] => Array
(
[time] => 1285571682
[user] => test2
)
How can I get the last value in the array, but maintaining the index [35]?
The outcome that I am looking for is this:
[35] => Array
(
[time] => 1285571682
[user] => test2
)
Solution 1:
try to use
end($array);
Solution 2:
$last = array_slice($array, -1, 1, true);
See http://php.net/array_slice for details on what the arguments mean.
P.S. Unlike the other answers, this one actually does what you want. :-)
Solution 3:
You can use end
to advance the internal pointer to the end or array_slice
to get an array only containing the last element:
$last = end($arr);
$last = current(array_slice($arr, -1));
Solution 4:
If you have an array
$last_element = array_pop(array);