最好的办法让一个数组的最后一个元素的w / o删除呢? [英] Best way to get last element of an array w/o deleting it?
本文介绍了最好的办法让一个数组的最后一个元素的w / o删除呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好吧,
我知道所有关于 array_pop()
,但删除最后一个元素。什么是得到一个数组的最后一个元素而不删除它的最佳方式?
编辑:这里有一个好处是:
$阵列=阵列('A'=>'一','B'=>'B','C'=>'C');
甚至
$阵列=阵列('A','B','C','D');
未设置($数组[2]);
回声$阵列[的sizeof($数组) - 1]; //输出:PHP公告:未定义抵消:在2 - 4号线
解决方案
简短而亲切。
$ lastEl = array_pop((array_slice($阵列,-1)));
请注意:需要额外的括号以避免 PHP严格的标准:只有变量应该按引用传递
Ok,
I know all about array_pop()
, but that deletes the last element. What's the best way to get the last element of an array without deleting it?
EDIT: Here's a bonus:
$array = array('a' => 'a', 'b' => 'b', 'c' => 'c');
or even
$array = array('a', 'b', 'c', 'd');
unset($array[2]);
echo $array[sizeof($array) - 1]; // Output: PHP Notice: Undefined offset: 2 in - on line 4
解决方案
Short and sweet.
$lastEl = array_pop((array_slice($array, -1)));
Note: The extra parentheses are needed to avoid a PHP Strict standards: Only variables should be passed by reference
.
这篇关于最好的办法让一个数组的最后一个元素的w / o删除呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文