Curly braces within double quoted strings in PHP
Archive - Originally posted on "The Horse's Mouth" - 2010-02-09 23:41:46 - Graham EllisIn PHP, you can include a variable name within a double quoted string and the variable will be expanded as the string is used - this means that double quotes are actually an operator, whereas single quotes mean a string literal. You can also put curly braces around a variable name to say, explicitly, "this is the variable", so:
$place = "London";
$course = "PHP";
print ("We can run a $course course for you in ${place} next month");
will produce:
We can run a PHP course for you in London next month
Somewhat surprisingly, you can also place the curly braces OUTSIDE the $, so the line:
print ("We can run a $course course for you in {$place} next month");
would produce the same results.
This use of curly braces outside the $ is known as the "complex" form of variable expansion within double quotes. In the other (simple) form, you can expand a regular variable, or an array member with a constant or simple variable name as its subscript - a very useful facility - but one which is frustratingly limited at times. In the complex form you have somewhat more facilities - you can use double subscripts ("arrays of arrays") and you can access object properties too. So:
print ("This is {$box->area()}\n");
is a valid (and very useful) syntax.
There's a full set of examples (with sample output) [here].