gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:17:27 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com