Is the behaviour of associative array keys in php 8.0.2 different to php 7? Should I enclose array keys in quotes, or not?

Viewed 747

Can anyone help me to understand what is happening here?
How do the double and single quotes affect the behaviour of the associative array keys?
Is this behaviour different to php 7, why?

      <?php
        // php version 8.0.2
        echo "$assoc_array[key]";   // OK
        echo  $assoc_array[key];    // error undefined constant "key"
        echo  $assoc_array['key'];  // OK
        echo "$assoc_array['key']"; // error - unexpected string content ""
        // this behaviour seems inconsistent
      ?>

This is my first question put to the forum. Please be gentle.

2 Answers

Let's take a look at each line...

echo  $assoc_array[key];

Anything string that isn't preceded with certain characters (e.g. $|->), terminated with certain characters (e.g. (), or inside of quotes (or heredoc etc.) is assumed to be a constant.

Which means key is usually assumed to be a constant. But you haven't set a constant value for key and therefore PHP has to do something with it...

Before PHP 8.x that would mean assume it was supposed to be a string and try the look up again; this would generate a warning.

This behaviour changed in PHP 8.x and now it throws an Error. Which, if not handled, ends the script.

echo "$assoc_array[key]";

In this case key is enclosed in quotes and thus, treated as a string. Arguably I'd suggest that this should throw an error as well; it would seem more consistent.

However, it's the same behaviour across PHP 7 & 8.

echo  $assoc_array['key'];

This is just the standard way to access an associative array; single or double quotes would be fine. Again, this behaviour is consistent across PHP versions.

echo "$assoc_array['key']";

This one's a bit trickier. What it comes down to is that using double quotes and variables is a tricky business. PHP has to try and decide what parts are meant literally and what parts are identifiers and the current process is that quotes around keys is not allowed.

This is consistent across PHP versions.


Effectively PHP provides two ways of defining variables inside of double quotes:

simple

This means a variable preceded with a $. Which can be used like:

echo "$variable";
echo "$array[key]";

Complex

This means almost any variable you can think of in PHP. Which is used like:

echo "{$variable}";
echo "${variable}
echo "{$array['key']}";
echo "${array['key']}";
echo "{$array["key"]}";
echo "${array["key"]}";
echo "{$object->property}";

See the PHP 7 >> 8 migration manual for further information on the backwards compatibility:

https://www.php.net/manual/en/migration80.incompatible.php

N.B. The key difference, for your purposes, is that the way undefined constants is handled has changed (as above) from a Warning to an Error Exception

Based on your code example, I used the following code to test:

<?php

$assoc_array = ['key' => 'okay'];

echo "$assoc_array[key]";   // OK
echo  $assoc_array[key];    // error undefined constant "key"
echo  $assoc_array['key'];  // OK
#echo "$assoc_array['key']"; // error - unexpected string content ""

Using PHP 7.2.34, I get the following results:

okayPHP Warning:  Use of undefined constant key - assumed 'key' (this will throw an Error in a future version of PHP) in /home/summea/example.php on line 6
okayokay

When I uncomment the last line from the above code, I get something like:

PHP Parse error:  syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in ...

Then, when running the above code in a PHP 8.0.0 editor online, I get:

okay<br />
<b>Fatal error</b>:  Uncaught Error: Undefined constant &quot;key&quot; in [...][...]:6
Stack trace:
#0 {main}
  thrown in <b>[...][...]</b> on line <b>6</b><br />

So, it appears that this PHP Warning: Use of undefined constant key warning from PHP 7.2.34 was changed into an Error at least by PHP 8.0.0.

When I uncomment the last line in the above code and run in PHP 8.0.0, I get:

<br />
<b>Parse error</b>:  syntax error, unexpected string content &quot;&quot;, expecting &quot;-&quot; or identifier or variable or number in <b>[...][...]</b> on line <b>8</b><br />

From these tests, I would recommend using the two general ideas below for this (for PHP 7.x.x and 8.0.0):

  • When dealing with an array_name[key] (without outer quotes), it seems safe to use this format: $array_name['key'].
  • When dealing with an "array_name[key]" (within outer quotes), it seems safe to use this format: "{$array_name['key']}".

Hopefully in answer to part of your questions, the "undefined constant key" error appears to happen because of a change between PHP 7.2.34 and PHP 8.0.0.

The "unexpected string content" error happens because I think you need to have {...} braces around an array with a key with single quotes when inside an outer double-quoted string in order to make it work. This particular behavior seems to be similar in both PHP 7.2.34 and PHP 8.0.0.

If, for example, you were to try using outer single quotes instead of double quotes, like this:

echo '{$assoc_array["key"]}';

In PHP 7.2.34 and PHP 8.0.0, the result should be:

{$assoc_array["key"]}

which is not quite what you want (it appears to be printing a literal version of your string). Thus, I would still recommend using the "{$array_name['key']}" format.

Related