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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6628/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:09:02  来源:igfitidea点击:

PHP array indexing: $array[$index] vs $array["$index"] vs $array["{$index}"]

phpsyntax

提问by svec

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
)

回答by

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.

在这种情况下,双引号将首先将 $index 复制到该字符串中,然后返回该字符串,而直接使用 $index 只会返回该字符串。

回答by svec

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"。时间是使用microtime()差异完成的。我使用的是 WinXP、PHP 5.2、Apache 2.2 和 Vim。:-)

And here are the results:

结果如下:

Using $idx = 0

使用 $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"

使用 $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"

使用 $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 到 4 次并得到了相同的结果。)

回答by Akira

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'] 比 $array[index] 快,其中 index 是一个string,而不是一个变量。那是因为如果你不把它用引号括起来,PHP 会寻找一个常量 var 并且找不到一个,所以假设你打算把它变成一个字符串。

回答by Jeremy Ruten

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 $indexis 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

回答by Jeremy Ruten

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:

电子垃圾:

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 作为索引?

回答by Jeremy Ruten

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] 不同的元素。

回答by ejunker

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] 快