Interpolation means placing a variable inside a string so PHP swaps in the value. It only works in double quotes (and heredocs).
<?php
$name = "Ravi";
$age = 30;
echo "$name is $age years old.";
Ravi is 30 years old.
When the next character is a letter
PHP reads the longest possible variable name. If a letter follows directly, wrap the variable in curly braces.
<?php
$fruit = "apple";
echo "I ate two ${fruit}s.\n"; // older style, deprecated in 8.2
echo "I ate two {$fruit}s."; // the style to use
Deprecated: Using ${var} in strings is deprecated, use {$var} instead in /path/to/index.php on line 4
I ate two apples.
I ate two apples.
The {$fruit} form with the dollar inside the braces is the one to use. The ${fruit} form is deprecated from PHP 8.2.
Array items
For arrays, use curly braces. They work with any key.
<?php
$user = ["name" => "Ravi", "city" => "Patna"];
echo "Hello, {$user['name']} from {$user['city']}.";
Hello, Ravi from Patna.
PHP also allows "$user[name]" without quotes around the key, but that looks confusing, and it is easy to get wrong. Use the curly braces.
Object properties and methods
<?php
class Product
{
public string $title = "Laptop";
public function price(): int
{
return 55000;
}
}
$p = new Product();
echo "Product: $p->title\n";
echo "Price: {$p->price()}";
Product: Laptop
Price: 55000
A simple property works without braces. A method call needs them.
Expressions are not allowed
You cannot calculate inside the quotes.
<?php
$price = 100;
echo "Total: {$price * 2}";
Parse error: syntax error, unexpected token "*", expecting "->" or "?->" or "{" or "[" in /path/to/index.php on line 4
PHP stops with a parse error. Calculate first, then print.
<?php
$price = 100;
$total = $price * 2;
echo "Total: $total";
Total: 200
Escaping a dollar sign
If you need a real $, put a backslash before it.
<?php
$amount = 50;
echo "Pay \$$amount";
Pay $50