phparraysindexed

Is Putting Quotes on PHP Named Indexes Unnecessary?


Is the following:

$arr = [
    foo => 'bar',
    bar => 'foo'
];

The same as:

$arr = [
    'foo' => 'bar',
    'bar' => 'foo'
];

In other words, is putting quotes on named indexes unnecessary? When would be the only times when putting quotes on string indexes be really needed?


Solution

  • Your first example should throw a NOTICE. If you do not use quotes then PHP will look for a constant with that name.

    php > $myArr = [abc => 'hello'];
    PHP Notice:  Use of undefined constant abc - assumed 'abc' in php shell code on line 1
    PHP Stack trace:
    PHP   1. {main}() php shell code:0
    
    Notice: Use of undefined constant abc - assumed 'abc' in php shell code on line 1
    
    Call Stack:
        9.7779     350840   1. {main}() php shell code:0
    

    I ran this example in PHP 7.1.8, however in PHP 7.2 this has been deprecated.