引用键访问数组 [英] Accessing arrays whitout quoting the key

查看:76
本文介绍了引用键访问数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

另请参见 Array做与不做 .

当使用用双引号引起来的变量解析您实际上需要编写不带引号的变量,或使用

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

这篇关于引用键访问数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆