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:
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).
See also Array do's and don'ts.
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:
[…] 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.
So:
// syntax error
echo "$array['key']";
// valid
echo "$array[key]";
echo "{$array['key']}";
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…