PHP: What is the fastest and easiest way to get the last item of an array?

筅森魡賤 提交于 2019-11-30 05:47:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!