Accessing arrays whitout quoting the key

前端 未结 3 1349
余生分开走
余生分开走 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:24

    PHP will raise a warning for the quote-less version ($array[key]) if there's no constant named keydefined, and silently convert it to $array['key']. Consider the trouble you'd have debugging your code if you had something:

    $array['foo'] = 'baZ'
    echo $array[foo];
    echo $array['foo'];
    echo "$array[foo]";
    echo "{$array['foo']}";
    echo "{$array[foo]}";
    
    define('foo', 'baR');
    echo $array[foo];
    echo $array['foo'];
    echo "$array[foo]";
    echo "{$array['foo']}";
    echo "{$array[foo]}";
    

    Try them out and see, but make sure you've got warnings enabled (error_reporting(E_ALL) and display_errors(1))

提交回复
热议问题