PHP - String String Interpolation

Introduction

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:

Demo

<?php
$cat = "cat";/*from www. j a va 2s .  c o  m*/
echo "My favorite animals are {$cat}s";
?>

Result

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.

Demo

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

Result