这些索引到PHP数组的方法之间有什么区别(如果有的话):
$array[$index]
$array["$index"]
$array["{$index}"]
Run Code Online (Sandbox Code Playgroud)
我对性能和功能差异感兴趣.
(回应@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);
Run Code Online (Sandbox Code Playgroud)
得到了这个输出:
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
)
Run Code Online (Sandbox Code Playgroud)
小智 33
见上面的@svec和@jeremy.所有数组索引首先是'int'类型,然后键入'string',并在PHP认为合适时将其强制转换为.
性能方面,$ index应该比"$ index"和"{$ index}"(它们相同)更快.
一旦你启动一个双引号字符串,PHP将进入插值模式并首先将其视为一个字符串,但寻找变量标记($,{}等)来替换本地范围.这就是为什么在大多数讨论中,真正的"静态"字符串应该始终是单引号,除非您需要转义快捷键,如"\n"或"\ t",因为PHP不需要尝试在运行时插入字符串和完整字符串可以静态编译.
在这种情况下,doublequoting将首先将$ index复制到该字符串中,然后返回字符串,其中直接使用$ index将返回字符串.
sve*_*vec 26
我计时使用这样的索引的3种方法:
for ($ii = 0; $ii < 1000000; $ii++) {
// TEST 1
$array[$idx] = $ii;
// TEST 2
$array["$idx"] = $ii;
// TEST 3
$array["{$idx}"] = $ii;
}
Run Code Online (Sandbox Code Playgroud)
使用的第一组测试,使用$idx=0的第二组测试$idx="0"和使用的第三组测试$idx="blah".使用microtime()差异进行计时.我正在使用WinXP,PHP 5.2,Apache 2.2和Vim.:-)
以下是结果:
$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
Run Code Online (Sandbox Code Playgroud)
$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
Run Code Online (Sandbox Code Playgroud)
$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
Run Code Online (Sandbox Code Playgroud)
所以$array[$idx]是性能的竞争,至少在我的机器上的双手向下赢家.(结果非常可重复,顺便说一句,我运行了3到4次,得到了相同的结果.)
我从性能角度相信$ array ["$ index"]比$ array [$ index]快,请参阅优化PHP代码性能的最佳实践
不要相信你所读到的所有内容......我认为你误解了这一点.文章说$ array ['index']比$ array [index]快,其中index是一个字符串,而不是一个变量.那是因为如果你不用引号将它包装起来,那么PHP会查找一个常量var并且找不到它,所以假设你想把它变成一个字符串.
不同的索引方法何时会解析为不同的索引?
根据http://php.net/types.array,数组索引只能是整数或字符串.如果您尝试使用float作为索引,它会将其截断为整数.所以,如果$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";
Run Code Online (Sandbox Code Playgroud)
输出:
Array([3] => float [3.14] => string)
float
string
Run Code Online (Sandbox Code Playgroud)