Accessing arrays whitout quoting the key

前端 未结 3 1347
余生分开走
余生分开走 2020-12-04 02:43

I can access an array value either with $array[key] or $array[\'key\']

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

3条回答
  •  一向
    一向 (楼主)
    2020-12-04 03:27

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

提交回复
热议问题