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 "key" 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 "", expecting "-" 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.