Skip to content

PHP Tutorial Strings

String Interpolation

Lesson 59 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Interpolation means placing a variable inside a string so PHP swaps in the value. It only works in double quotes (and heredocs).

index.php
PHP
<?php
$name = "Ravi";
$age = 30;

echo "$name is $age years old.";
Output
OUTPUT
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.

index.php
PHP
<?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
Output
OUTPUT
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.

index.php
PHP
<?php
$user = ["name" => "Ravi", "city" => "Patna"];

echo "Hello, {$user['name']} from {$user['city']}.";
Output
OUTPUT
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

index.php
PHP
<?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()}";
Output
OUTPUT
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.

index.php
PHP
<?php
$price = 100;

echo "Total: {$price * 2}";
Output
OUTPUT
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.

index.php
PHP
<?php
$price = 100;
$total = $price * 2;

echo "Total: $total";
Output
OUTPUT
Total: 200

Escaping a dollar sign

If you need a real $, put a backslash before it.

index.php
PHP
<?php
$amount = 50;
echo "Pay \$$amount";
Output
OUTPUT
Pay $50
lightbulb
Prefer sprintf for complex output
When a sentence has many values or needs number formatting, sprintf() is easier to read than long interpolated strings.