String Interpolation

Double-quoted strings insert variable values directly into the text.

Syntaxecho "Hello, $name!"; echo "Total: {$price}";

When you use double quotes, PHP replaces variable names with their values. This is called interpolation.

Single-quoted strings do not do this — a $name inside single quotes is printed literally. Use curly braces {$var} to make the boundaries clear.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Embed a username directly inside a double-quoted welcome-email subject line.
  • Build a dynamic SQL LIKE pattern by inserting a search term inside a heredoc string.
  • Interpolate an array value inside a template string using curly brace syntax.

More examples

Basic variable interpolation

Variables inside double-quoted strings are expanded; prefix a literal dollar sign with a backslash or double it.

Example · php
<?php
$product = 'Widget';
$price   = 9.99;

echo "Product: $product — Price: $$price";

Curly brace syntax

Curly braces delimit complex expressions inside strings, such as array lookups or object property access.

Example · php
<?php
$status  = 'active';
$colors  = ['active' => 'green', 'inactive' => 'red'];

echo "Status color: {$colors[$status]}";

Interpolating object properties

Object property access inside strings requires curly braces to disambiguate the -> arrow from surrounding text.

Example · php
<?php
$user = new stdClass();
$user->name  = 'Bob';
$user->email = '[email protected]';

echo "Welcome, {$user->name}! Your email is {$user->email}.";

Discussion

  • Be the first to comment on this lesson.