Variable Substitution

Variable substitution is a way to embed data held in a variable directly into string literals. PHP parse double-quoted (and heredoc) strings and replace variable names with the variable’s value.

Variable substitution provides a convenient way to output variables embedded in string literals. When PHP parses double-quoted or heredoc strings, variable names are identified when a $ character is found and the value of the variable is substituted. The following example shows how:

$num = 3;
$vehicle = 'car';

echo "This $vehicle holds $num people";
// prints "This car holds 3 people"

PHP interprets the $ and the following non-space characters as the name of a variable to insert. To include the dollar signs in a double-quoted string you need to escape the variable substitution meaning with the backslash sequence \$.

Curly braces in string

When the name of the variable is ambiguous, braces {} can delimit the name as shown in the following example:

$memory = 32;

//Error, undefined variable $memoryGB
echo "My laptop has $memoryGB of RAM";

// Works: braces are used delimit variable name
echo "My laptop has {$memory}GB of RAM";

When the string literal containing the characters $memoryGB is parsed, PHP tries to substitute the value of the nonexisting variable $memoryGB. Braces are also used for more complex variables, such as arrays and objects:

$dbQuery = new stdClass();
$dbQuery->count = 10;

$arr = ['one'=>1, 'two'=>2];
$planets = ['Earth'=>['dia'=>12756], 'Mars'=>['dia'=>6779]];

//Prints: The first array element value is 1.
print "The first array element value is {$arr['one']}.";

//Prints: Mars diameter: 6779
print "Mars diameter: {$planets['Mars']['dia']}";

//Prints: There are 10 results ...
print "There are {$dbQuery->count} results ...";

Single-quoted (and nowdoc) strings aren’t parsed in the same way as double-quoted strings for variable substitution. For example, the characters $vehicle and $num aren’t substituted in the following example:

$num = 3;
$vehicle = 'car';

// prints "This $vehicle holds $num people"
print 'This $vehicle holds $num people';

Getting Started with PHP:

  1. Introducing PHP
  2. PHP Development Environment
  3. Variable Assignment, Expressions, and Operators
  4. Delimiting Strings
  5. Variable Substitution
  6. Constants