PHP string interpolation syntax

Quoting the manual:

When a string is specified in double quotes or with heredoc, variables are parsed within it.

There are two types of syntax: a simple one and a complex one. The simple syntax is the most common and convenient. It provides a way to embed a variable, an array value, or an object property in a string with a minimum of effort.

The complex syntax can be recognised by the curly braces surrounding the expression.

Your first code uses simple syntax, and your second code uses a complex one.

The manual does not explicitly state this, but whitespace in simple syntax seems to be an error, rendering your first code invalid. Complex syntax appears to support the same syntax as regular PHP does as far as I can see, but again this does not seem to be actually guaranteed anywhere.

String interpolation is quite flunky in general:

$a = [['derp']];
$b = $a[0];

// Works. It prints derp
echo "$b[0]";

// Doesn't work. It throws an error
echo "$b[ 0 ]";

// Works. It prints derp
echo "{$b[ 0 ]}";

// Doesn't work. It prints Array[0]
echo "$a[0][0]";

// Works. It prints derp
echo "{$a[0][0]}";

// Doesn't work. It prints { Array[0] }
echo "{ $a[0][0] }";

You get similar issues with $object -> foo and $object->foo->bar.

To me, that is pure madness. For that reason I’ve come to avoid double quoted strings whenever possible (the only thing I used them for are for escape sequences like "\n"). I instead use single quotes and string concatenation, like so:

header( 'location: readMore.php?id=' . $post[ 'post_id' ] );

This lets you use actual PHP syntax for variables without the horrible death trap that is string interpolation.

Leave a Comment