php - 在不引用 key 的情况下访问数组

标签 php syntax

我可以使用 $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).

另见 Array do's and don'ts .

现在与在普通 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/

相关文章:

php - 如何从域的根目录中包含 PHP?

c - 错误: Expected ')' before 'packet'

python - 如何以方便的数学方式输入公式来绘制矢量场?

php - 在 PHP 中使用 Heredoc Notation 的优点和缺点是什么?

php - 按索引合并两个数组

php - 无法插入数据库

Python/Ubuntu - 将目录复制到新目录(目录路径不正确?)

Perl "\my $var"为什么 "my"用反斜杠转义?

php - 按日期列出的最后三个条目的平均值

php - Cakephp ACL ARO_ACO