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?
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?
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
I would say array_pop
In the documentation: array_pop
array_pop — Pop the element off the end of array
$myArray = array( 5, 4, 3, 2, 1 );
echo end($myArray);
prints "1"
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
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.)