This error is most often encountered when attempting to reference an array value with a quoted key for interpolation inside a double-quoted string, when the entire complex variable construct is not enclosed in
{}
.The error case:
This will result in
Unexpected T_ENCAPSED_AND_WHITESPACE
:echo "This is a double-quoted string with a quoted array key in $array['key']";
//---------------------------------------------------------------------^^^^^
Possible fixes:
In a double-quoted string, PHP will permit array key strings to be used unquoted, and will not issue an
E_NOTICE
. So the above could be written as:echo "This is a double-quoted string with an un-quoted array key in $array[key]";
//------------------------------------------------------------------------^^^^^
The entire complex array variable and key(s) can be enclosed in
{}
, in which case they should be quoted to avoid an E_NOTICE
. The PHP documentation recommends this syntax for complex variables.echo "This is a double-quoted string with a quoted array key in {$array['key']}";
//--------------------------------------------------------------^^^^^^^^^^^^^^^
// Or a complex array property of an object:
echo "This is a a double-quoted string with a complex {$object->property->array['key']}";
Of course, the alternative to any of the above is to concatenate the array variable in instead of interpolate it:
echo "This is a double-quoted string with an array variable " . $array['key'] . " concatenated inside.";
//----------------------------------------------------------^^^^^^^^^^^^^^^^^^^^^
For reference, see the section on Variable Parsing in the PHP Strings manual page