问题
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?
回答1:
$myArray = array( 5, 4, 3, 2, 1 );
echo end($myArray);
prints "1"
回答2:
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
回答3:
try this:
$arrayname[count(arrayname)-1]
回答4:
I would say array_pop
In the documentation: array_pop
array_pop — Pop the element off the end of array
回答5:
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.)
回答6:
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
来源:https://stackoverflow.com/questions/1927029/php-what-is-the-fastest-and-easiest-way-to-get-the-last-item-of-an-array