-2

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?

GTS Joe
  • 3,612
  • 12
  • 52
  • 94
  • 2
    Doesn't your first version throw warnings? – Federico klez Culloca Mar 19 '18 at 14:57
  • See https://stackoverflow.com/q/2406006/354577 – ChrisGPT was on strike Mar 19 '18 at 14:57
  • 1
    Turn PHP notices on - the unquoted version is trying to use constants named `foo` and `bar`. The default behaviour until PHP 7.2 was to raise a notice and fall back to the name of the constant. This has now been increased to a warning, and will likely stop working as of PHP 8. In short, this is never (and has never been) a good idea. – iainn Mar 19 '18 at 14:57

2 Answers2

6

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.

Jim Wright
  • 5,905
  • 1
  • 15
  • 34
0

PHP converts "bare strings" into proper strings, but will give you a warning. It is likely that this functionality will disappear in future.

If you really, really want to do this (you shouldn't), it will work as log as the string matches the format for a constant, which is the regex

[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

(Don't do it. Just don't.)

lonesomeday
  • 233,373
  • 50
  • 316
  • 318