tags:

views:

82

answers:

5

I have an array like this:

[33] => Array
    (
        [time] => 1285571561
        [user] => test0
    )

[34] => Array
    (
        [time] => 1285571659
        [user] => test1
    )

[35] => Array
    (
        [time] => 1285571682
        [user] => test2
    )

How i can get the last value in the array, but maintaining the index [35]?

Edit: my goal is get something like this:

    [35] => Array
        (
            [time] => 1285571682
            [user] => test2
        )
+3  A: 

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));
Gumbo
but i need to preserve the index, like:[35] => Array ( [time] => 1285571682 [user] => test2 )
greenbandit
If you need to preserve the index, you could use array_slice(). See http://stackoverflow.com/questions/3801891/get-last-value-in-array/3802007#3802007
Martijn Heemels
+5  A: 

try to use

end($array);
Alexander.Plutov
A: 

Like said Gumbo,

<?php

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

?>
Isern Palaus
A: 
$index = count($a) - 1;
$b[$index] = $a[$index];

$b should contain (index 35) variables time and user.

Webarto
What if the array is custom indexed?
Lo'oris
35 is a number, it is not association. What are you talking about?
Webarto
+2  A: 
$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. :-)

salathe