CodeBlanks Logo Icon CodeBlanks

Variable interpolation in double quotes

PHP course · Beginner · Lesson 33/116

Learn how variables are interpolated inside double-quoted strings and the use of {} braces.

Variable interpolation in double quotes

In PHP, when you write a variable name inside a double-quoted string, PHP places the variable's value into the string. For example, $name = "Alex"; echo "Hello $name"; outputs "Hello Alex". This is called variable interpolation.

In single quotes, $name is written as is; echo 'Hello $name'; outputs "Hello $name". This difference helps you choose which quote to use.

When do you need curly braces?

Inside a double-quoted string, writing $variable is usually enough. But when a letter comes right after the variable name, PHP gets confused. For example, "$names" makes PHP look for a variable named $names; you may have wanted to append the letter s to $name.

Curly braces {} solve this: "{$name}s" outputs Alexs. The same rule applies to array elements and property access. In complex expressions, always use {} to be safe.

Exercise Build a message with interpolation

Assign "Alex" to $name. Assign "Hello, $name!" to $msg using double quotes (use variable interpolation). Then print it with echo $msg;.

Show example solution
Use double quotes; $name inside the string is replaced by its value.
Example solution:
<?php
$name = "Alex";
$msg = "Hello, $name!";
echo $msg;

Test yourself

  1. $city = "Paris"; echo "City: $city"; what is the output?

    $city = "Paris";
    echo "City: $city";
    • City: $city
    • City: Paris
    • City:
    • It errors
    Show answer

    City: Paris — Correct. Double quotes place the value of $city: "City: Paris".

  2. Insert the variable with curly braces

    $product = 'Coffee';
    echo "Product: ____";
    Show answer
    $product = 'Coffee';
    echo "Product: {$product}";
  3. Match each syntax to its behavior

    '$name'
    No interpolation
    "$name"
    Interpolates the variable
    "{$name}"
    Curly-brace interpolation

All lessons in Beginner