skip to content

Quoting & Interpolation

Single quotes are literal; double quotes and heredoc interpolate $var and {$expr}, while nowdoc never does. Interviewers check escape sequences, the deprecated ${var} form and byte offsets.

part ofPHPoverview, primer and where to startread it →
on this pageshow

explore

questions

5

In PHP, what is the difference between single-quoted and double-quoted strings?

level: juniorimportance: must knowfreq 75%

answer

  1. one is literal, one is parsed
  2. single quotes: only \' and \\
  3. double quotes: \n, \t, \$, \u{...}
  4. variables expand only in double quotes
  5. speed difference is a myth

basics

~10 s

Single-quoted strings are literal: only ' and \ are escapes and variables are not expanded. Double-quoted strings interpret escape sequences such as \n, \t and \u{...} and interpolate variables like $name.

solid answer

~40 s

A **single-quoted** string is taken almost literally: the only escapes are `\'` for a quote and `\\` for a backslash, so `'Hi\n$name'` contains a backslash, an `n` and a dollar sign. A **double-quoted** string is parsed: escape sequences such as `\n`, `\t`, `\\`, `\$`, `\"`, octal `\101`, hex `\x41` and `\u{00E9}` become the characters they name, and variables such as `$name` or `{$user->email}` are replaced by their values. An unknown escape like `\d` is kept as backslash plus letter. Both are compiled once, so there is no meaningful speed difference; pick single quotes for literal text such as regex patterns and paths, and double quotes when you need escapes or interpolation.

code

php · 10 lines
php
<?php
declare(strict_types=1);

$firstName = 'Ada';

echo 'Hello $firstName\n', PHP_EOL;  // Hello $firstName\n  (literal)
echo "Hello $firstName\n";           // Hello Ada + newline
echo 'It\'s due: C:\\bills', PHP_EOL; // It's due: C:\bills
echo "Price: \$40\tcaf\u{00E9}\n";   // Price: $40<TAB>café
echo "Pattern: \d+\n";              // Pattern: \d+ (unknown escape kept)

go deeper

for a junior

Recall that single quotes are literal apart from ' and \, and that only double quotes expand variables and escapes such as \n.

for a middle

List the double-quote escape sequences, including octal, hex and \u{...}, and explain what happens to unknown escapes and to \u without braces.

for a senior

Choose quoting by intent, keep regex patterns in single quotes, and flag interpolation into SQL, HTML or shell strings as an escaping bug.

for a principal

Let a coding-standard rule decide quote style so reviews focus on meaning, and treat any interpolation into an interpreter context as an escaping design issue.

## Two ways to write a string literal PHP has four string literal syntaxes: single-quoted, double-quoted, heredoc and nowdoc. The first two are the everyday ones, and they differ in one thing: **how much PHP parses between the quotes**. | | Single quotes `'…'` | Double quotes `"…"` | |---|---|---| | Escape sequences | only `\'` and `\\` | the full set below | | Variable interpolation | none | `$var`, `$arr[0]`, `$obj->prop`, `{$expr}` | | A literal `$` | just type it | write `\$` (or ensure no name follows) | | Unknown escape like `\d` | kept as `\d` | kept as `\d` | ## Single quotes: literal text Inside single quotes, everything is literal except two escapes: - `\'` produces a single quote: `'It\'s at 9:00'`. - `\\` produces one backslash. A lone backslash before any other character is also kept, so `'C:\temp'` works, but doubling it is the unambiguous habit. So `'Line one\nLine two'` is one line containing the two characters `\` and `n`, and `'Hello $name'` contains the text `$name`. ## Double quotes: escapes and interpolation Double-quoted strings interpret these **escape sequences**: - `\n` line feed, `\r` carriage return, `\t` tab, `\v` vertical tab, `\e` escape, `\f` form feed; - `\\` backslash, `\$` dollar sign, `\"` double quote; - `\101` octal (1 to 3 digits), `\x41` hexadecimal (1 or 2 digits); - `\u{00E9}` a Unicode code point, written out as its UTF-8 bytes; the braces are required. A few edge cases are worth knowing. `\u` **without** braces is left alone, so JSON-like text such as `"\u00e9"` passes through unchanged, while a malformed `\u{zz}` is a parse error ("Invalid UTF-8 codepoint escape sequence"). An octal escape above `\377` wraps to fit in one byte, and the compiler emits a warning about the overflow. Double quotes also **interpolate variables**: `"Hi $name"` becomes `Hi Ada` when `$name` is `'Ada'`. The details of what can be embedded (array elements, properties, `{$expr}`) are a topic of their own; the point here is that only double-quoted strings and heredocs do it at all. ## An appointment-reminder example Building the plain-text body of a reminder email shows where each style fits: ```php $greeting = "Hello $firstName,\n\n"; // interpolation + newlines $line = "Your appointment is at {$slot->time}.\n"; $footer = 'Reply STOP to opt out. Fees are in $ (USD).'; // literal $ ``` The first two need double quotes for `\n` and the variables. The footer uses single quotes so the dollar sign and any backslashes stay literal without escaping. ## The speed myth An old claim says single quotes are faster because PHP does not scan them for variables. String literals are parsed once when the script is compiled (and OPcache keeps the compiled result), so a double-quoted string without variables ends up as the same constant as its single-quoted twin. Any difference is far below anything a profiler would show. Choose by meaning, not speed. ## Mistakes that show up in review - **A `\n` in single quotes** meant as a newline, which ends up as two literal characters in an email or log line. - **A `$` in double quotes** followed by letters, such as a price template `"Pay $amount now"` that was meant literally; PHP interpolates `$amount` (or warns that it is undefined). - **Windows paths in double quotes**, where `"C:\temp\new"` turns `\t` and `\n` into a tab and a newline. - **Doubled escaping** after switching quote style, such as leaving `\'` inside a double-quoted string, where it prints the backslash too. ## Practical conventions 1. Use **single quotes** by default for literal text: array keys, SQL fragments with placeholders, regex patterns (where `\d` and `\s` must reach the regex engine intact), Windows paths. 2. Use **double quotes** when you need a newline or tab escape, or when interpolation reads more clearly than concatenation. 3. Do not interpolate into **SQL, HTML or shell commands**; interpolation performs no escaping at all. Use prepared statements and the escaping functions meant for each context. 4. Many coding standards and fixers can enforce single quotes where no interpolation or escape is used, which keeps the choice consistent across a codebase.

  • Why are regex patterns usually written in single quotes in PHP?
    Patterns are full of backslashes (`\d`, `\s`, `\.`). In single quotes those reach the regex engine unchanged. In double quotes most still survive because unknown escapes are kept, but sequences PHP does recognise, such as `\t`, `\$` or `\x41`, are converted first, which changes the pattern in ways that are easy to miss.
  • How do you put a literal dollar sign before a word in a double-quoted string?
    Escape it: `"Cost: \$total"` prints `Cost: $total`. A `$` that is not followed by a character that can start a variable name is also kept as-is, as in `"$ 40"`, but escaping makes the intent explicit. Switching that string to single quotes avoids the question entirely.

saying these in an interview costs you the question

  • Single quotes interpret \n as a newline
  • Double-quoted strings are noticeably slower even without variables
  • An unknown escape like \d is removed from a double-quoted string
  • Interpolation escapes values, so it is safe for SQL
  • Single quotes have no escape sequences at all
open as a page

In PHP, what can simple $var interpolation embed in a double-quoted string, and when do you need the {$expr} curly syntax?

level: middleimportance: must knowfreq 50%

basics

~10 s

Simple syntax embeds a variable, one array element with an unquoted key or number, or one property: "$name", "$arr[0]", "$obj->prop". Anything deeper, quoted keys or method calls need curly syntax: "{$obj->a->b}", "{$arr['key']}".

open as a page

In PHP, how do $s[0] and $s[-1] read single characters of a string, and what happens with an offset past the end?

level: juniorimportance: should knowfreq 35%

basics

~20 s

$s[0] returns the first byte of a string as a one-character string and $s[-1] the last. Reading past the end gives an E_WARNING, Uninitialized string offset, and an empty string. Offsets count bytes, not characters.

open as a page

In PHP, how do heredoc and nowdoc strings differ, and what does the flexible closing marker introduced in PHP 7.3 allow?

level: middleimportance: should knowfreq 40%

basics

~20 s

Heredoc (<<<EOT) is a multi-line double-quoted string that interpolates variables and escapes; nowdoc (<<<'EOT') is its literal, single-quoted twin. Since PHP 7.3 the closing marker may be indented, and that indentation is removed from every line.

open as a page

After an upgrade to PHP 8.2 or later, logs fill with 'Using ${var} in strings is deprecated' notices; what triggers them and how do you fix each form?

level: seniorimportance: should knowfreq 22%

basics

~10 s

PHP 8.2 deprecated the ${...} interpolation syntax. "${name}" and "${name['key']}" become "{$name}" and "{$name['key']}"; any other "${expr}" is a variable variable and becomes "{${expr}}". PHP 8.5 still only deprecates it.

open as a page