PHP - String String Interpolation


You can insert a variable's value in a double-quoted string simply by including the variable's name preceded by a $ symbol.

You can use the curly brackets to distinguish the variable name from the rest of the string.

Consider the following situation:

$cat = "cat";
echo "My favorite animals are $cats";

This code is ambiguous.

Should PHP insert the value of the $cat variable followed by an "s" character?

To get around this problem using curly brackets, as follows:


$cat = "cat";//from w  w w  .  j  a v a  2  s.c  om
echo "My favorite animals are {$cat}s";


You can place the opening curly bracket after the $ symbol, which has the same effect:

echo "My favorite animals are ${cat}s";

You can use curly bracket syntax to insert more complex variable values, such as array element values and object properties.


$myArray["age"] = 4;
echo "My age is {$myArray["age"]}"; 
echo "My age is " . $myArray["age"];