PHP数组索引:$array[$index] vs $array[" $index "] vs $array[" {$index} "]

时间:2022-06-05 00:37:23

What is the difference, if any, between these methods of indexing into a PHP array:

这些索引方法与PHP数组之间的区别是什么?

$array[$index]
$array["$index"]
$array["{$index}"]

I'm interested in both the performance and functional differences.

我对性能和功能差异都感兴趣。

Update:

(In response to @Jeremy) I'm not sure that's right. I ran this code:

(回应@Jeremy)我不确定这是对的。我跑这段代码:

  $array = array(100, 200, 300);
  print_r($array);
  $idx = 0;
  $array[$idx] = 123;
  print_r($array);
  $array["$idx"] = 456;
  print_r($array);
  $array["{$idx}"] = 789;
  print_r($array);

And got this output:

,这个输出:

Array
(
    [0] => 100
    [1] => 200
    [2] => 300
)

Array
(
    [0] => 123
    [1] => 200
    [2] => 300
)

Array
(
    [0] => 456
    [1] => 200
    [2] => 300
)

Array
(
    [0] => 789
    [1] => 200
    [2] => 300
)

7 个解决方案

#1


29  

see @svec and @jeremy above. All array indices are of type 'int' first, then type 'string', and will be cast to that as PHP sees fit.

见@svec和@jeremy。所有数组索引都是“int”类型的,然后键入“string”,并将其转换为PHP认为合适的类型。

Performance wise, $index should be faster than "$index" and "{$index}" (which are the same).

性能方面,$index应该比“$index”和“{$index}”(它们是相同的)更快。

Once you start a double-quote string, PHP will go into interpolation mode and treat it as a string first, but looking for variable markers ($, {}, etc) to replace from the local scope. This is why in most discussions, true 'static' strings should always be single quotes unless you need the escape-shortcuts like "\n" or "\t", because PHP will not need to try to interpolate the string at runtime and the full string can be compiled statically.

一旦启动了双引号字符串,PHP就会进入插值模式,并将其作为字符串首先处理,但是要寻找变量标记($,{}等)来替换本地范围。这就是为什么在大多数讨论中,真正的“静态”字符串应该始终是单引号,除非您需要像“\n”或“\t”这样的快捷键,因为PHP不需要尝试在运行时插入字符串,而完整的字符串可以静态编译。

In this case, doublequoting will first copy the $index into that string, then return the string, where directly using $index will just return the string.

在这种情况下,doublequote首先将$index复制到该字符串中,然后返回字符串,在这里直接使用$index将返回字符串。

#2


24  

I timed the 3 ways of using an index like this:

我选择了3种方法来使用这样的索引:

for ($ii = 0; $ii < 1000000; $ii++) {
   // TEST 1
   $array[$idx] = $ii;
   // TEST 2
   $array["$idx"] = $ii;
   // TEST 3
   $array["{$idx}"] = $ii;
}

The first set of tests used $idx=0, the second set used $idx="0", and the third set used $idx="blah". Timing was done using microtime() diffs. I'm using WinXP, PHP 5.2, Apache 2.2, and Vim. :-)

第一组测试使用$idx=0,第二组使用$idx="0",第三组使用$idx="blah"。时间是利用微时间()扩散的。我使用的是WinXP、PHP 5.2、Apache 2.2和Vim。:-)

And here are the results:

结果如下:

Using $idx = 0

$array[$idx]            // time: 0.45435905456543 seconds
$array["$idx"]          // time: 1.0537171363831 seconds
$array["{$idx}"]        // time: 1.0621709823608 seconds
ratio "$idx" / $idx     // 2.3191287282497
ratio "{$idx}" / $idx   // 2.3377348193858

Using $idx = "0"

$array[$idx]            // time: 0.5107250213623 seconds
$array["$idx"]          // time: 0.77445602416992 seconds
$array["{$idx}"]        // time: 0.77329802513123 seconds
ratio "$idx" / $idx     // = 1.5163855142717
ratio "{$idx}" / $idx   // = 1.5141181512285

Using $idx = "blah"

$array[$idx]           // time: 0.48077392578125 seconds
$array["$idx"]         // time: 0.73676419258118 seconds
$array["{$idx}"]       // time: 0.71499705314636 seconds
ratio "$idx" / $idx    // = 1.5324545551923
ratio "{$idx}" / $idx  // = 1.4871793473086

So $array[$idx] is the hands-down winner of the performance competition, at least on my machine. (The results were very repeatable, BTW, I ran it 3 or 4 times and got the same results.)

因此,$array ($idx)是性能竞争的最终赢家,至少在我的机器上是这样。(结果是非常重复的,顺便说一下,我跑了三四次,结果都一样。)

#3


6  

I believe from a performance perspective that $array["$index"] is faster than $array[$index] See Best practices to optimize PHP code performance

我相信,从性能的角度来看,$array[“$index”]比$array[$index]更快地看到了优化PHP代码性能的最佳实践。

Don't believe everything you read so blindly... I think you misinterpreted that. The article says $array['index'] is faster than $array[index] where index is a string, not a variable. That's because if you don't wrap it in quotes PHP looks for a constant var and can't find one so assumes you meant to make it a string.

不要盲目相信你所读的一切……我想你误解了。这篇文章说,$array['index']比数组[索引]更快,索引是一个字符串,而不是一个变量。这是因为如果你不把它用引号括起来,PHP就会找一个常量var,找不到一个,假设你想把它变成一个字符串。

#4


5  

When will the different indexing methods resolve to different indices?

不同的索引方法何时会解析到不同的索引?

According to http://php.net/types.array, an array index can only be an integer or a string. If you try to use a float as an index, it will truncate it to integer. So if $index is a float with the value 3.14, then $array[$index] will evaluate to $array[3] and $array["$index"] will evaluate to $array['3.14']. Here is some code that confirms this:

根据http://php.net/types.array,数组索引只能是整数或字符串。如果您尝试使用浮点数作为索引,它会将它截断为整数。因此,如果$index是带有值3.14的浮点数,那么$array[$index]将计算$array[3]和$array["$index"]将计算为$array['3.14']。下面是一些确认这一点的代码:

$array = array(3.14 => 'float', '3.14' => 'string');
print_r($array);

$index = 3.14;
echo $array[$index]."\n";
echo $array["$index"]."\n";

The output:

输出:

Array([3] => float [3.14] => string)
float
string

#5


1  

Response to the Update:

Oh, you're right, I guess PHP must convert array index strings to numbers if they contain only digits. I tried this code:

哦,你是对的,我猜PHP必须将数组下标字符串转换为数字,如果它们只包含数字。我试着这段代码:

$array = array('1' => 100, '2' => 200, 1 => 300, 2 => 400);
print_r($array);

And the output was:

和输出是:

Array([1] => 300 [2] => 400)

I've done some more tests and found that if an array index (or key) is made up of only digits, it's always converted to an integer, otherwise it's a string.

我做了更多的测试,发现如果一个数组索引(或键)只由数字组成,那么它总是被转换成一个整数,否则它就是一个字符串。

ejunker:

ejunker:

Can you explain why that's faster? Doesn't it take the interpreter an extra step to parse "$index" into the string to use as an index instead of just using $index as the index?

你能解释一下为什么这更快吗?它不需要一个额外的步骤来解析“$index”作为索引,而不是仅仅使用$index作为索引吗?

#6


0  

If $index is a string there is no difference because $index, "$index", and "{$index}" all evaluate to the same string. If $index is a number, for example 10, the first line will evaluate to $array[10] and the other two lines will evaluate to $array["10"] which is a different element than $array[10].

如果$index是字符串,则没有区别,因为$index、“$index”和“{$index}”都将对相同的字符串进行计算。如果$index是一个数字,例如10,第一行将计算$array[10],另外两行将计算$array["10"],这是一个不同于$array的元素[10]。

#7


-5  

I believe from a performance perspective that $array["$index"] is faster than $array[$index] See Best practices to optimize PHP code performance

我相信,从性能的角度来看,$array[“$index”]比$array[$index]更快地看到了优化PHP代码性能的最佳实践。

Another variation that I use sometimes when I have an array inside a string is:

当我在字符串中有一个数组时,我使用的另一个变体是:

$str = "this is my string {$array["$index"]}";

Edit: What I meant to say is $row[’id’] is faster than $row[id]

编辑:我想说的是$row[' id ']比$row[id]要快

#1


29  

see @svec and @jeremy above. All array indices are of type 'int' first, then type 'string', and will be cast to that as PHP sees fit.

见@svec和@jeremy。所有数组索引都是“int”类型的,然后键入“string”,并将其转换为PHP认为合适的类型。

Performance wise, $index should be faster than "$index" and "{$index}" (which are the same).

性能方面,$index应该比“$index”和“{$index}”(它们是相同的)更快。

Once you start a double-quote string, PHP will go into interpolation mode and treat it as a string first, but looking for variable markers ($, {}, etc) to replace from the local scope. This is why in most discussions, true 'static' strings should always be single quotes unless you need the escape-shortcuts like "\n" or "\t", because PHP will not need to try to interpolate the string at runtime and the full string can be compiled statically.

一旦启动了双引号字符串,PHP就会进入插值模式,并将其作为字符串首先处理,但是要寻找变量标记($,{}等)来替换本地范围。这就是为什么在大多数讨论中,真正的“静态”字符串应该始终是单引号,除非您需要像“\n”或“\t”这样的快捷键,因为PHP不需要尝试在运行时插入字符串,而完整的字符串可以静态编译。

In this case, doublequoting will first copy the $index into that string, then return the string, where directly using $index will just return the string.

在这种情况下,doublequote首先将$index复制到该字符串中,然后返回字符串,在这里直接使用$index将返回字符串。

#2


24  

I timed the 3 ways of using an index like this:

我选择了3种方法来使用这样的索引:

for ($ii = 0; $ii < 1000000; $ii++) {
   // TEST 1
   $array[$idx] = $ii;
   // TEST 2
   $array["$idx"] = $ii;
   // TEST 3
   $array["{$idx}"] = $ii;
}

The first set of tests used $idx=0, the second set used $idx="0", and the third set used $idx="blah". Timing was done using microtime() diffs. I'm using WinXP, PHP 5.2, Apache 2.2, and Vim. :-)

第一组测试使用$idx=0,第二组使用$idx="0",第三组使用$idx="blah"。时间是利用微时间()扩散的。我使用的是WinXP、PHP 5.2、Apache 2.2和Vim。:-)

And here are the results:

结果如下:

Using $idx = 0

$array[$idx]            // time: 0.45435905456543 seconds
$array["$idx"]          // time: 1.0537171363831 seconds
$array["{$idx}"]        // time: 1.0621709823608 seconds
ratio "$idx" / $idx     // 2.3191287282497
ratio "{$idx}" / $idx   // 2.3377348193858

Using $idx = "0"

$array[$idx]            // time: 0.5107250213623 seconds
$array["$idx"]          // time: 0.77445602416992 seconds
$array["{$idx}"]        // time: 0.77329802513123 seconds
ratio "$idx" / $idx     // = 1.5163855142717
ratio "{$idx}" / $idx   // = 1.5141181512285

Using $idx = "blah"

$array[$idx]           // time: 0.48077392578125 seconds
$array["$idx"]         // time: 0.73676419258118 seconds
$array["{$idx}"]       // time: 0.71499705314636 seconds
ratio "$idx" / $idx    // = 1.5324545551923
ratio "{$idx}" / $idx  // = 1.4871793473086

So $array[$idx] is the hands-down winner of the performance competition, at least on my machine. (The results were very repeatable, BTW, I ran it 3 or 4 times and got the same results.)

因此,$array ($idx)是性能竞争的最终赢家,至少在我的机器上是这样。(结果是非常重复的,顺便说一下,我跑了三四次,结果都一样。)

#3


6  

I believe from a performance perspective that $array["$index"] is faster than $array[$index] See Best practices to optimize PHP code performance

我相信,从性能的角度来看,$array[“$index”]比$array[$index]更快地看到了优化PHP代码性能的最佳实践。

Don't believe everything you read so blindly... I think you misinterpreted that. The article says $array['index'] is faster than $array[index] where index is a string, not a variable. That's because if you don't wrap it in quotes PHP looks for a constant var and can't find one so assumes you meant to make it a string.

不要盲目相信你所读的一切……我想你误解了。这篇文章说,$array['index']比数组[索引]更快,索引是一个字符串,而不是一个变量。这是因为如果你不把它用引号括起来,PHP就会找一个常量var,找不到一个,假设你想把它变成一个字符串。

#4


5  

When will the different indexing methods resolve to different indices?

不同的索引方法何时会解析到不同的索引?

According to http://php.net/types.array, an array index can only be an integer or a string. If you try to use a float as an index, it will truncate it to integer. So if $index is a float with the value 3.14, then $array[$index] will evaluate to $array[3] and $array["$index"] will evaluate to $array['3.14']. Here is some code that confirms this:

根据http://php.net/types.array,数组索引只能是整数或字符串。如果您尝试使用浮点数作为索引,它会将它截断为整数。因此,如果$index是带有值3.14的浮点数,那么$array[$index]将计算$array[3]和$array["$index"]将计算为$array['3.14']。下面是一些确认这一点的代码:

$array = array(3.14 => 'float', '3.14' => 'string');
print_r($array);

$index = 3.14;
echo $array[$index]."\n";
echo $array["$index"]."\n";

The output:

输出:

Array([3] => float [3.14] => string)
float
string

#5


1  

Response to the Update:

Oh, you're right, I guess PHP must convert array index strings to numbers if they contain only digits. I tried this code:

哦,你是对的,我猜PHP必须将数组下标字符串转换为数字,如果它们只包含数字。我试着这段代码:

$array = array('1' => 100, '2' => 200, 1 => 300, 2 => 400);
print_r($array);

And the output was:

和输出是:

Array([1] => 300 [2] => 400)

I've done some more tests and found that if an array index (or key) is made up of only digits, it's always converted to an integer, otherwise it's a string.

我做了更多的测试,发现如果一个数组索引(或键)只由数字组成,那么它总是被转换成一个整数,否则它就是一个字符串。

ejunker:

ejunker:

Can you explain why that's faster? Doesn't it take the interpreter an extra step to parse "$index" into the string to use as an index instead of just using $index as the index?

你能解释一下为什么这更快吗?它不需要一个额外的步骤来解析“$index”作为索引,而不是仅仅使用$index作为索引吗?

#6


0  

If $index is a string there is no difference because $index, "$index", and "{$index}" all evaluate to the same string. If $index is a number, for example 10, the first line will evaluate to $array[10] and the other two lines will evaluate to $array["10"] which is a different element than $array[10].

如果$index是字符串,则没有区别,因为$index、“$index”和“{$index}”都将对相同的字符串进行计算。如果$index是一个数字,例如10,第一行将计算$array[10],另外两行将计算$array["10"],这是一个不同于$array的元素[10]。

#7


-5  

I believe from a performance perspective that $array["$index"] is faster than $array[$index] See Best practices to optimize PHP code performance

我相信,从性能的角度来看,$array[“$index”]比$array[$index]更快地看到了优化PHP代码性能的最佳实践。

Another variation that I use sometimes when I have an array inside a string is:

当我在字符串中有一个数组时,我使用的另一个变体是:

$str = "this is my string {$array["$index"]}";

Edit: What I meant to say is $row[’id’] is faster than $row[id]

编辑:我想说的是$row[' id ']比$row[id]要快