String Interpolation

Ma Mariya Vinciya Updated 17 Oct 2026
9 min read ·Lesson 45 of 102
In this post

What Is String Interpolation? In simple terms: String interpolation means writing a variable directly inside a string so that PHP replaces it with the variable's value. Technically: When PHP parses a

What Is String Interpolation?

In simple terms: String interpolation means writing a variable directly inside a string so that PHP replaces it with the variable's value.

Technically: When PHP parses a double-quoted string or a heredoc, it scans for $ followed by a valid variable name (and optionally array or property access). It replaces that part of the string with the value converted to a string. This process is also called variable parsing or variable substitution.

Why Interpolation Exists

Compare the same sentence written two ways:

<?php
$name = "Divya";
$course = "PHP";
$progress = 75;

echo "Hi " . $name . ", you have completed " . $progress . "% of " . $course . ".\n";
echo "Hi $name, you have completed $progress% of $course.\n";

Output

Hi Divya, you have completed 75% of PHP.
Hi Divya, you have completed 75% of PHP.

The interpolated version reads like the final sentence. It has fewer quotes and dots to manage, so it is easier to write and to scan for typos.

Where Interpolation Works

String TypeInterpolation?
Double-quoted "..."Yes
Heredoc <<<IDYes
Single-quoted '...'No
Nowdoc <<<'ID'No

Simple Syntax

The simple syntax is a $ followed by a variable name, written directly in the string.

Variables

<?php
$city = "Trichy";
$temperature = 34;

echo "It is $temperature°C in $city today.";

Output

It is 34°C in Trichy today.

Where Does the Variable Name End?

PHP reads the longest possible valid variable name: letters, digits, and underscores after $. Any other character ends the name.

<?php
$fruit = "apple";

echo "I like $fruits.\n";
echo "I like {$fruit}s.\n";

Output

PHP Warning:  Undefined variable $fruits in /path/script.php on line 4
I like .
I like apples.

In the first line, PHP reads $fruits (because s is a valid name character) and finds no such variable. The curly-brace syntax, explained below, marks exactly where the name ends.

Array Elements

In the simple syntax, array keys are written without quotes:

<?php
$user = ['name' => 'Mohan', 'role' => 'admin'];
$scores = [88, 92, 79];

echo "User: $user[name], role: $user[role]\n";
echo "First score: $scores[0], third score: $scores[2]\n";

Output

User: Mohan, role: admin
First score: 88, third score: 79
  • $user[name] inside a string means the element with the string key name. (Outside of strings, an unquoted key would be an error.)
  • Numeric indexes such as $scores[0] work directly.

Note: PHP arrays do not support negative indexes that count from the end. "$scores[-1]" looks for an element whose key is literally -1, which does not exist here, so PHP raises an "Undefined array key -1" warning. (Negative offsets from the end work for strings, such as $text[-1].) To show the last array element, store it in a variable first: $last = end($scores);, or use array_last($scores) in PHP 8.5+.

Quoted Keys Are Not Allowed in Simple Syntax

<?php
$user = ['name' => 'Mohan'];
echo "User: $user['name']";

This is a parse error: inside the simple syntax, a quoted key is not allowed. Either remove the quotes ($user[name]) or use the curly-brace syntax ({$user['name']}), which is clearer and is the recommended form.

Object Properties

<?php
$product = new stdClass();
$product->title = "Wireless Earbuds";
$product->price = 2499;

echo "$product->title costs ₹$product->price\n";

Output

Wireless Earbuds costs ₹2499

The simple syntax supports one level of property access. For nested properties such as $order->customer->name, use curly braces.


Curly-Brace (Complex) Syntax

The curly-brace syntax wraps the expression in { and }. The { must be immediately followed by $.

Syntax

"{$expression}"

What It Supports

<?php
$user = [
    'name' => 'Lakshmi',
    'address' => ['city' => 'Erode'],
];

$order = new stdClass();
$order->id = 5021;
$order->customer = new stdClass();
$order->customer->email = "lakshmi@example.com";

$date = new DateTime('2026-10-08');
$item = "notebook";

echo "Name: {$user['name']}\n";
echo "City: {$user['address']['city']}\n";
echo "Order {$order->id} for {$order->customer->email}\n";
echo "Date: {$date->format('d M Y')}\n";
echo "Two {$item}s\n";

Output

Name: Lakshmi
City: Erode
Order 5021 for lakshmi@example.com
Date: 08 Oct 2026
Two notebooks

How It Works

ExpressionWhat It Shows
{$user['name']}Array element with a quoted key — the same syntax as normal PHP code
{$user['address']['city']}Nested array access
{$order->customer->email}Nested object properties
{$date->format('d M Y')}A method call on an object
{$item}sClear boundary between the variable name and following text

The rule of thumb: inside {$ ... }, you can write any expression that starts with a variable — array access, property access, and method calls — exactly as you would outside a string.

What It Does Not Support

Function calls and constants are not interpolated, because they do not start with $:

<?php
$name = "ravi";

echo "Name: {strtoupper($name)}\n";
echo "Version: PHP_VERSION\n";

Output

Name: {strtoupper(ravi)}
Version: PHP_VERSION
  • {strtoupper( does not start with {$, so the braces and function name are printed literally and only $name is interpolated.
  • Constant names such as PHP_VERSION are plain text inside strings.

Arithmetic is not allowed inside the braces either: "{$a + $b}" is a parse error, because $a + $b is not a variable expression.

For these cases, use concatenation or sprintf():

<?php
$a = 5;
$b = 3;

echo "Name: " . strtoupper($name) . "\n";
echo "Version: " . PHP_VERSION . "\n";
echo "Sum: " . ($a + $b) . "\n";

The Deprecated ${...} Syntax

Older code may use a dollar sign outside the braces:

<?php
$name = "Asha";
echo "Hello ${name}";

Since PHP 8.2, this form produces:

PHP Deprecated:  Using ${var} in strings is deprecated, use {$var} instead

It is scheduled for removal in a future major version. Replace "${name}" with "{$name}" or "$name".

SyntaxStatus
"$name"Supported
"{$name}"Supported (recommended for anything beyond a simple variable)
"${name}"Deprecated since PHP 8.2
"${expr}" (variable variables in strings)Deprecated since PHP 8.2

Printing a Literal $ or {

Dollar Sign

<?php
$amount = 50;

echo "Price: \$amount\n";
echo "Price: \$$amount\n";
echo 'Price: $amount' . "\n";

Output

Price: $amount
Price: $50
Price: $amount
  • \$ escapes the dollar sign, so $amount is not interpolated.
  • \$$amount prints a literal $ followed by the value of $amount.
  • Single quotes never interpolate.

A $ that is not followed by a valid variable name (such as $5 or $ ) is printed as-is, but escaping it explicitly makes the intent clear.

Curly Brace Followed by $

<?php
$x = 10;

echo "Braces: {\$x}\n";
echo "Set: { $x }\n";

Output

Braces: {$x}
Set: { 10 }

{\$ prints {$ without starting the complex syntax. A { followed by a space is not special at all, so { $x } prints the braces and interpolates $x using the simple syntax.


How Values Are Converted

Interpolated values are converted to strings with the same rules as echo and concatenation:

<?php
$count = 3;
$ratio = 0.50;
$active = true;
$deleted = false;
$note = null;
$tags = ['php', 'web'];

echo "Count: $count | Ratio: $ratio | Active: $active | Deleted: [$deleted] | Note: [$note]\n";
echo "Tags: $tags\n";

Output

Count: 3 | Ratio: 0.5 | Active: 1 | Deleted: [] | Note: []
PHP Warning:  Array to string conversion in /path/script.php on line 10
Tags: Array
ValueAppears As
Integer 33
Float 0.500.5
true1
false, nullempty
ArrayArray plus a warning
Object without __toString()Fatal Error

To show formatted values, prepare them first:

<?php
$ratioText = number_format($ratio * 100) . '%';
$activeText = $active ? 'Yes' : 'No';
$tagText = implode(', ', $tags);

echo "Ratio: $ratioText | Active: $activeText | Tags: $tagText\n";

Output

Ratio: 50% | Active: Yes | Tags: php, web

Interpolation vs Concatenation vs sprintf()

ApproachStrengthsWeaknesses
Interpolation "Hi $name"Most readable for simple valuesNo function calls, no formatting
Concatenation "Hi " . ucfirst($name)Works with any expressionMany quotes and dots in long strings
sprintf("Hi %s", $name)Precise formatting, reusable templatesValues are separated from their positions in the text

A practical guideline:

  • Use interpolation when the string contains plain variables, array elements, or properties.
  • Use concatenation when you need a function call in one or two places.
  • Use sprintf() when numbers need formatting or the template is reused or translated.

Interpolation and Security

Interpolation is only a way of building a string. It does not make values safe for the place where the string is used.

HTML

<?php
$comment = '<script>alert(1)</script>';

echo "<p>$comment</p>";                            // unsafe
echo "<p>" . htmlspecialchars($comment) . "</p>"; // safe

Since function calls cannot be interpolated, escape the value first and interpolate the result:

<?php
$safeComment = htmlspecialchars($comment);
echo "<p>$safeComment</p>";

SQL

<?php
// DANGEROUS: SQL injection
$sql = "SELECT * FROM users WHERE email = '$email'";

Never interpolate input into SQL. Use prepared statements with placeholders (see PDO Prepared Statements).


Practical Example: Building a Notification Message

<?php
$user = ['first_name' => 'Senthil', 'plan' => 'Pro'];

$invoice = new stdClass();
$invoice->number = 'INV-2026-0098';
$invoice->amount = 1499;
$invoice->dueDate = new DateTime('2026-10-15');

$amountText = number_format($invoice->amount, 2);

$message = "Hi {$user['first_name']},\n"
    . "Your {$user['plan']} plan invoice {$invoice->number} for ₹$amountText "
    . "is due on {$invoice->dueDate->format('l, d F')}.\n";

echo $message;

Output

Hi Senthil,
Your Pro plan invoice INV-2026-0098 for ₹1,499.00 is due on Thursday, 15 October.

Step-by-Step Explanation

  1. {$user['first_name']} reads an array element with a quoted key — clear and safe from boundary problems.
  2. {$invoice->number} reads an object property.
  3. $amountText is prepared beforehand with number_format(), because function calls cannot be interpolated.
  4. {$invoice->dueDate->format('l, d F')} calls a method on a nested object. l is the full weekday name, d the day with a leading zero, and F the full month name.
  5. Long messages are split into several double-quoted parts joined with ., which keeps each source line short while still using interpolation.

Common Mistakes

Using Single Quotes

Effect: 'Hello $name' prints $name literally.

Fix: Use double quotes.

Variable Name Running Into Following Text

Effect: "$fruits" is read as a variable named $fruits — undefined variable warning.

Fix: "{$fruit}s".

Quoted Keys in Simple Syntax

Effect: Parse error for "$user['name']".

Fix: "{$user['name']}".

Nested Properties Without Braces

Effect: "$order->customer->email" interpolates only $order->customer, then tries to convert that object to a string, which causes an error.

Fix: "{$order->customer->email}".

Expecting Functions or Constants to Interpolate

Effect: Text such as {strtoupper(...)} or PHP_VERSION appears literally.

Fix: Use concatenation, sprintf(), or prepare a variable first.

Using the Deprecated ${var} Form

Effect: Deprecation notices in PHP 8.2+.

Fix: Use {$var}.

Assuming Negative Array Indexes Count From the End

Effect: "$items[-1]" looks for the key -1 and usually finds nothing.

Fix: Get the last element first: $last = end($items); (or array_last($items) in PHP 8.5+).


Best Practices

  • Use "{$var}" braces for array elements, nested properties, method calls, and whenever text follows the variable directly.
  • Keep interpolated expressions simple; prepare formatted or computed values in variables first.
  • Use single quotes for strings that contain no variables.
  • Escape values for their destination (HTML, SQL, URLs) before or instead of interpolating them.
  • Replace deprecated ${var} syntax when maintaining older code.

Official reference: https://www.php.net/manual/en/language.types.string.php#language.types.string.parsing

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else Slicing Strings User-defined Functions Slicing Strings PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting
Ask about this post
AI Ask about this post

Ask questions about String Interpolation and get answers drawn from it.

Signed-in readers only.