在不引用键的情况下访问数组

2021-12-29 00:00:00 syntax php

我可以使用 $array[key]$array['key']

是否有理由避免使用一种而不是另一种?

Is there a reason to avoid using one over the other?

推荐答案

使用后一种变体 $array['key'].前者只会工作,因为 PHP 是宽容的,如果没有名为 key 的常量,则假定字符串值 key:

Use the latter variant $array['key']. The former will only work because PHP is tolerant and assumes the string value key if there is no constant named key:

始终在字符串文字数组索引周围使用引号.例如, $foo['bar'] 是正确的,而 $foo[bar] 则不是.[...] 这是错误的,但它有效.原因是这个 […] 有一个未定义的常量 (bar) 而不是字符串 ('bar' - 注意引号).

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 代码中访问数组相反,当使用 双引号字符串中的变量解析 您实际上需要在不带引号的情况下编写它或使用 花括号语法:

Now in opposite to accessing arrays in plain PHP code, when using variable parsing in double quoted strings you actually need to write it without quotes or use the curly brace syntax:

[...] 在双引号字符串中,数组索引不包含引号是有效的,所以 "$foo[bar]" 是有效的.有关原因的详细信息以及有关字符串中变量解析的部分,请参见上述示例.

[…] 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']}";

相关文章