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
    )
728x90

9 Answers Get last key-value pair in PHP array

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));

8 year ago

try to use

end($array);

8 year ago

Like said Gumbo,

<?php

$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry

?>

8 year ago

$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. :-)

8 year ago

// if your array keys lile
// 0 1 2 3 4 ...

$lastindex= count($ar)-1;

// but if you are not sure

$ar_k=array_keys($ar);
$lastindex=$ar_k[count($ar_k)-1];

// will work

8 year ago

If you have an array

$last_element = array_pop(array);

3 year ago

Another solution cold be:

$value = $arr[count($arr) - 1];

The above will count the amount of array values, substract 1 and then return the value.

Note: This can only be used if your array keys are numeric.

3 year ago

As the key is needed, the accepted solution doesn't work.

This:

end($array);
return array(key($array) => array_pop($array));

will return exactly as the example in the question.

3 year ago

"SPL-way":

$splArray = SplFixedArray::fromArray($array);
$last_item_with_preserved_index[$splArray->getSize()-1] = $splArray->offsetGet($splArray->getSize()-1);

Read more about SplFixedArray and why it's in some cases ( especially with big-index sizes array-data) more preferable than basic array here => The SplFixedArray class.

1 weeks ago