Search code examples
phpassociative-arrayphp-7php-8

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?


Can anyone help me 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
      ?>

Solution

  • 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