我可以使用 $array[key]
或 $array['key']
访问数组值
是否有理由避免在另一个之上使用一个?
最佳答案
使用后一种变体 $array['key']
。前者之所以有效,是因为 PHP 具有容错性,如果没有名为 key 的常量,则假定字符串值为 key
:
Always use quotes around a string literal array index. For example,
$foo['bar']
is correct, while$foo[bar]
is not. […] This is wrong, but it works. The reason is that this […] has an undefined constant (bar
) rather than a string ('bar'
- notice the quotes).
现在与在普通 PHP 代码中访问数组相反,当使用 variable parsing in double quoted strings 时你实际上需要在不带引号的情况下编写它或使用 curly brace syntax :
[…] inside a double-quoted string, it's valid to not surround array indexes with quotes so
"$foo[bar]"
is valid. See the above examples for details on why as well as the section on variable parsing in strings.
所以:
// syntax error
echo "$array['key']";
// valid
echo "$array[key]";
echo "{$array['key']}";
关于php - 在不引用 key 的情况下访问数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3891832/