views:

218

answers:

6

Hello All,

What is the fastest and easiest way to get the last item of an array whether be indexed array , associative array or multi-dimensional array?

+3  A: 

array_pop()

It removes the element from the end of the array. If you need to keep the array in tact, you could use this and then append the value back to the end of the array. $array[] = $popped_val

munch
+1 for being faster :D
Matt Ellen
+1  A: 

I would say array_pop In the documentation: array_pop

array_pop — Pop the element off the end of array

Matt Ellen
+25  A: 
$myArray = array( 5, 4, 3, 2, 1 );

echo end($myArray);

prints "1"

code-zoop
and to get the last element's key... (to update it)`end($myArray); $key=key($myArray);`
ZJR
+2  A: 

try this:

$arrayname[count(arrayname)-1]
Treby
This is wrong, it only works with ordered numerical array, ie it won't work with shuffled or associative array.
Niteriter
A: 

For an associative array:

$a= array('hi'=> 'there', 'ok'=> 'then');
list($k, $v) = array(end(array_keys($a)), end($a));
var_dump($k);
var_dump($v);

Edit: should also work for numeric index arrays

pygorex1
`$v=end($a); $k=key($a);` (order IS relevant) seems faster to me.
ZJR
+1  A: 

Lots of great answers. Consider writing a function if you're doing this more than once:

function array_top(&$array) {
    $top = end($array);
    reset($array); // Optional
    return $top;
}

Alternatively, depending on your temper:

function array_top(&$array) {
    $top = array_pop($array);
    $array[] = $top; // Push top item back on top
    return $top;
}

($array[] = ... is preferred to array_push(), cf. the docs.)

jensgram