简体   繁体   English

PHP-访问数组末尾计数元素的优雅(快速)方法?

[英]PHP - elegant (fast) way to access elements counting from end of array?

I've got an array where I want to grab the "negative three" element regardless of array length. 我有一个数组,无论数组长度如何,我都希望获取“负三”元素。 (If that doesn't make sense throw out a comment and I'll clarify). (如果那没有道理,请发表评论,我会澄清)。

The obvious way to do it is $arr[count($arr)-4] but this feels clunky. 显而易见的方法是$arr[count($arr)-4]但这感觉很笨拙。

Is there a quick, elegant way to do this? 有没有一种快速,优雅的方法来做到这一点?

UPDATE 更新

Still fiddling, any thoughts regarding this? 还在摆弄,对此有什么想法吗?

array_slice($arr,-4,-3); 

Yes there is: 就在这里:

Try something like this: 尝试这样的事情:

$newArray = array_slice($array, -3);

The obvious way returns the single value you want in constant time, assuming you have numeric indexes. 假设您有数字索引,则显而易见的方法是在恒定时间内返回所需的单个值。 The array size is known to PHP already, it just jumps to the offset you want and gives you the result. 数组大小已为PHP所熟知,它只是跳转到所需的偏移量并为您提供结果。

array_slice does many times as much work, comparing the array size to your offset, computing the loop conditions, creating a new array to store the slice, looping over the portion of the existing array, copying the values into the new array, then returning that array to you. array_slice完成许多工作,将数组大小与偏移量进行比较,计算循环条件,创建一个新的数组来存储切片,循环遍历现有数组的一部分,将值复制到新数组中,然后返回数组给你。

http://lxr.php.net/opengrok/xref/PHP_TRUNK/ext/standard/array.c http://lxr.php.net/opengrok/xref/PHP_TRUNK/ext/standard/array.c

you could use $last = end($arr); 您可以使用$last = end($arr); then use prev($arr); 然后使用prev($arr); twice to get 2 other elements. 两次以获得2个其他元素。

Oh, and check if these return FALSE, in case you don't have at least 3 elements. 哦,如果您没有至少3个元素,请检查它们是否返回FALSE。

array_slice()吗?

array_slice($a, -3)

尝试使用array_slice()函数,将负偏移量作为第二个参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM