String Interpolation
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 Type | Interpolation? |
|---|---|
Double-quoted "..." | Yes |
Heredoc <<<ID | Yes |
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 keyname. (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 usearray_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
| Expression | What 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}s | Clear 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$nameis interpolated.- Constant names such as
PHP_VERSIONare 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".
| Syntax | Status |
|---|---|
"$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$amountis not interpolated.\$$amountprints 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
| Value | Appears As |
|---|---|
Integer 3 | 3 |
Float 0.50 | 0.5 |
true | 1 |
false, null | empty |
| Array | Array 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()
| Approach | Strengths | Weaknesses |
|---|---|---|
Interpolation "Hi $name" | Most readable for simple values | No function calls, no formatting |
Concatenation "Hi " . ucfirst($name) | Works with any expression | Many quotes and dots in long strings |
sprintf("Hi %s", $name) | Precise formatting, reusable templates | Values 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
{$user['first_name']}reads an array element with a quoted key — clear and safe from boundary problems.{$invoice->number}reads an object property.$amountTextis prepared beforehand withnumber_format(), because function calls cannot be interpolated.{$invoice->dueDate->format('l, d F')}calls a method on a nested object.lis the full weekday name,dthe day with a leading zero, andFthe full month name.- 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