php PHP中数组的负索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6889663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Negative index of array in PHP
提问by Jeg Bagus
I found some code that uses negative array indices. Then, I try to use it, nothing special happens. It behaves normally. I can retrieve all elements by using a standard foreach
loop.
我发现了一些使用负数组索引的代码。然后,我尝试使用它,没有什么特别的事情发生。它的行为正常。我可以使用标准foreach
循环检索所有元素。
So, what is the purpose to use those negative indices? And when should I use it?
那么,使用这些负指数的目的是什么?我应该什么时候使用它?
采纳答案by Pascal MARTIN
An array, in PHP, is actually just some kind of an ordered map : you can use integers (positive or negative), but also strings, as keys -- and there will not be much of difference.
在 PHP 中,数组实际上只是某种有序映射:您可以使用整数(正数或负数),也可以使用字符串作为键——并且不会有太大区别。
回答by Jeremy Roman
Negative array keys have no special meaning in PHP, as (like any other value) they can be the keys of an associative array.
负数组键在 PHP 中没有特殊含义,因为(像任何其他值一样)它们可以是关联数组的键。
$arr = array(-1 => 5);
echo $arr[-1];
Some of PHP's standard library functions (the ones that expect regular arrays with only natural integer indices), however, take negative offsets to mean "count from the end instead of the beginning". array_slice
is one such example.
然而,一些 PHP 的标准库函数(那些期望只有自然整数索引的常规数组的函数)采用负偏移量来表示“从末尾而不是开头计数”。array_slice
就是这样的一个例子。
回答by Sz.
From 7.1 onward, we have an important and practical special case, i.e. when using the array syntax to access particular characters of a string from backwards:
从 7.1 开始,我们有一个重要且实用的特殊情况,即当使用数组语法从后访问字符串的特定字符时:
$str = "123";
$empty = "";
echo "LAST CHAR of str == '$str[-1]'<br>"; // '3'
echo "LAST CHAR of empty == '$empty[-1]'<br>"; // '', Notice: Uninitialized string offset: -1
回答by bugos
Negative array indexes don't have a special meaning (i.e. get the last/second last element etc.) in PHP. To get the last element of an array use:
负数组索引在 PHP 中没有特殊含义(即获取最后/倒数第二个元素等)。要获取数组的最后一个元素,请使用:
$last = end($array);
To get the second last add:
要获得倒数第二个添加:
$secondLast = prev($array);
Keep in mind that these functions modify the arrays internal pointer. To reset it use:
请记住,这些函数会修改数组内部指针。要重置它,请使用:
reset($array);