Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 147 · Data Types

Strings

Learn PHP strings - single vs double quotes, escape sequences, variable interpolation with braces, heredoc and nowdoc, string bytes and concatenation.

A string is a piece of text: a name, an email address, a line of HTML, a whole JSON document. PHP was built to produce web pages, so it's no surprise that strings are the type you'll use most. Almost everything that comes into a PHP program (form fields, URL parameters, file contents, database rows) arrives as a string, and almost everything that goes out is a string too.

PHP gives you four ways to write a string literal: single quotes, double quotes, heredoc and nowdoc. They differ in one key way: whether PHP looks inside the text for variables and escape sequences. This lesson walks through all four, shows how to build strings by joining pieces together, and explains what a PHP string really is underneath (a sequence of bytes), which matters the moment your text contains letters like é or ü.

You already met echo in Output: echo, print, printf and variables in Variables. Here you'll put them together. The many functions that work on strings (searching, replacing, trimming) get their own lesson later: String Functions.

Single-quoted strings

The simplest string is written between single quotes. PHP takes the text almost exactly as you typed it:

PHP Single quotes are literal

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Run it and look closely at the output:

TEXT
Hello, $name!
Line one\nstill line one
It's a backslash: \
A lone backslash \ stays as it is

Inside single quotes, $name is just five characters, not a variable, and \n is a backslash followed by the letter n, not a new line. Only two escape sequences work in single quotes:

  • \' puts a single quote inside the string.
  • \\ puts one backslash. You only need it when a backslash comes right before a quote or at the very end of the string; a backslash before any other character is kept as it is.

Because nothing inside is interpreted, single quotes are the safest and clearest choice for plain text. The style used throughout this tutorial (and by most PHP projects) is: use single quotes unless you need what double quotes offer.

Double-quoted strings

Double quotes do two extra things: they understand escape sequences, and they interpolate variables, which means they replace a variable's name with its value.

PHP Escapes and variables in double quotes

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is:

TEXT
Product:	Keyboard
Price:	$49.5
She said "hi" and left.
Unicode: 😀 é

Here are the escape sequences you'll actually use in double-quoted strings:

Escape Meaning
\n New line (line feed)
\t Tab
\r Carriage return
\\ One backslash
\$ A literal dollar sign, so PHP doesn't start a variable
\" A double quote
\u{1F600} The Unicode character with that hex code point, written as UTF-8
\x41 The byte with hex value 41 (the letter A)
\0, \101 A byte given in octal (\101 is also A)

An unknown escape such as \q is left alone: you get the backslash and the q. That's forgiving, but it also means a typo doesn't produce an error, so double-check paths like "C:\new\folder", where \n silently becomes a line break. Windows paths and regular expressions are good reasons to reach for single quotes.

On the web, \n doesn't create a visible line break in the browser, because HTML collapses whitespace. It still matters for the page source, for text files, emails and the command line. Our editor shows plain text, like a terminal, so \n breaks lines here.

Interpolation: variables inside strings

Writing "Hello, $name" is called string interpolation. PHP reads the longest valid variable name after the $ and swaps in its value. That "longest name" rule is where surprises come from:

PHP Simple interpolation and its limits

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Lines 7 to 9 work as you'd hope. Line 10 is a mistake on purpose: PHP looks for a variable called $fruits, which doesn't exist, so you get a warning and an empty value:

TEXT
I ate 3 apples.
Name: Lin, first color: red
Total: 30 items

Warning: Undefined variable $fruits in main.php on line 10
I ate 3 .

The fix is the curly-brace syntax: wrap the variable in { and } so PHP knows exactly where it ends. "{$fruit}s" means "the value of $fruit, then an s". The opening { must be immediately followed by $.

Simple interpolation (without braces) understands one level of array index or property:

  • "$user[name]": an array element with an unquoted string key (only in this simple form).
  • "$colors[0]": an element with an integer key.
  • "$order->id": an object property.

For anything more, use braces. Inside { } you write the expression exactly as you would in normal code, quotes and all:

PHP Curly braces for complex expressions

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Braces work with nested arrays, object properties, and method calls ("{$cart->total()}"), but not with arbitrary expressions such as function calls or arithmetic. "{$a + $b}" is a parse error. Compute the value first, or use concatenation or sprintf() (covered in Formatting Strings).

You may see an older form, "${name}", with the dollar sign outside the braces. It was deprecated in PHP 8.2 and produces a deprecation notice. Always write "{$name}".

Heredoc: multi-line strings with interpolation

When a string spans many lines (an email body, an HTML fragment, a SQL query), quotes and \n get messy. Heredoc syntax starts with <<< and an identifier of your choice, and ends with the same identifier on its own line. It behaves like a double-quoted string, so variables and escapes work, but you don't need to escape double quotes.

PHP A heredoc email

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Since PHP 7.3, the closing marker may be indented, and PHP removes that same amount of indentation from every line of the body. Here the marker TEXT; has four spaces before it, so four spaces are stripped from each line; the signature line keeps its two extra spaces:

TEXT
Hi Marta,

Thanks for your order "A-778".
We'll ship your 2 items tomorrow.
  - The Shop Team

Two rules keep heredocs from failing:

  • The body lines must be indented at least as much as the closing marker. A body line with less indentation is a parse error.
  • Don't mix tabs and spaces in the indentation of the body and the marker.

The final newline before the closing marker is not part of the string. That's why the output above has no blank line at the end.

Nowdoc: multi-line strings without interpolation

Nowdoc is to heredoc what single quotes are to double quotes. You write the identifier in single quotes: <<<'CODE'. Nothing inside is interpreted, which is perfect for code samples, templates with literal $ signs, or regular expressions:

PHP Nowdoc keeps everything literal

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output shows the code exactly as written, with $price and \n untouched; our outer $price variable is never used:

TEXT
<?php
$price = $base * 1.2;
echo "Price: $price\n";
---
51 characters

Joining strings: the dot operator

PHP uses a dot (.) to join, or concatenate, strings. It doesn't use +, which is always numeric addition in PHP. The compound form .= appends to an existing variable, which is handy for building output piece by piece:

PHP Concatenation with . and .=

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is:

TEXT
Grace Hopper
<ul><li>tea</li><li>coffee</li><li>juice</li></ul>
Year: 1907

On a web server, the browser would render that second line as a bulleted list; our editor shows the HTML source. (The drinks are fixed strings here; text that comes from users must be escaped with htmlspecialchars() before it goes into HTML, as you'll learn in PHP and HTML Templates.)

The last line mixes . and + in one expression. Since PHP 8, the arithmetic operators + and - bind more tightly than ., so PHP reads it as 'Year: ' . (1906 + 1) . "\n" and prints Year: 1907. In PHP 7 and older, the same line was evaluated left to right as ('Year: ' . 1906) + 1, which tried to add 1 to a non-numeric string. Code that relies on either rule is hard to read, so add parentheses whenever you mix concatenation with math.

Concatenation converts numbers to strings automatically: 'Total: ' . 42 gives 'Total: 42'. Floats are rounded to 14 significant digits when they become strings, so 'Sum: ' . (0.1 + 0.2) gives 'Sum: 0.3' even though the stored value is very slightly more. You'll see why in Integers and Floats.

Interpolation or concatenation?

Both produce the same result, so pick whichever reads better:

PHP
$greeting = "Hello, {$user['name']}! You have {$count} new messages.";
$greeting = 'Hello, ' . $user['name'] . '! You have ' . $count . ' new messages.';

Interpolation is usually easier to read for sentences. Concatenation is clearer when you mix in function calls. For precise number formatting (two decimals, padding), use sprintf(). Performance differences are too small to matter.

Strings are sequences of bytes

A PHP string is not a list of "characters" in the human sense. It's a sequence of bytes, and PHP doesn't store which text encoding they use. Any byte value can appear, even a zero byte, so strings can hold binary data like images too.

You can read a single byte with square brackets, just like an array. Index 0 is the first byte, and negative indexes (PHP 7.1+) count from the end:

PHP Indexing and the byte trap

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

strlen() counts bytes. For plain English letters, that's the same as characters. But source files and web pages use UTF-8, where letters like ü take two bytes (and emoji take four). So strlen('Zürich') is 7, not 6, and $city[1] is only the first half of ü, an invalid byte on its own. var_dump shows it as string(1) followed by a broken character. Put the two halves back together and the letter reappears.

For text that may contain non-English characters, use the multibyte functions such as mb_strlen() and mb_substr(). They're covered in depth in Unicode and Multibyte Strings.

Strings are values in PHP. $b = $a; gives $b its own copy of the text, so changing $b[0] later never changes $a. (PHP shares the memory until one copy is modified, a trick called copy-on-write, so assignment is cheap even for long strings.)

Assigning past the end pads the string with spaces: $s = 'ab'; $s[4] = 'z'; makes 'ab z'. Reading past the end gives a warning (Uninitialized string offset) and an empty string. Both are rarely what you want, so check lengths first.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What does this print? $n = 5; echo 'Count: $n';

    Single-quoted strings never interpolate variables, so $n is printed literally as two characters.
  2. 2. Which line correctly prints the value of $data['user'] inside a double-quoted string?

    Curly braces with the dollar sign inside let you write the full expression, quoted key included. The first form is a parse error, and ${...} has been deprecated since PHP 8.2.
  3. 3. Which operator joins two strings in PHP?

    The dot is PHP's concatenation operator, and .= appends to a variable. The + operator is always numeric addition.
  4. 4. What does strlen('café') return in a UTF-8 file?

    strlen counts bytes, and é takes two bytes in UTF-8, so the four visible characters take five bytes. mb_strlen would return 4.
  5. 5. How does a nowdoc differ from a heredoc?

    A nowdoc (<<<'ID') treats its body literally, like a single-quoted string. A heredoc (<<<ID) behaves like a double-quoted string.

Summary

  • Single quotes are literal: only \' and \\ are special. Prefer them for plain text.
  • Double quotes process escapes (\n, \t, \$, \u{...}) and interpolate variables.
  • Use curly braces ("{$order['id']}", "{$item}s") whenever a variable is followed by letters or you need a quoted key, nested arrays or method calls. Never use the deprecated "${name}" form.
  • Heredoc (<<<ID) is a multi-line double-quoted string; nowdoc (<<<'ID') is a multi-line single-quoted string. The closing marker's indentation is removed from every line.
  • The dot . concatenates, and .= appends.
  • A PHP string is a sequence of bytes: strlen() counts bytes and $s[0] reads one byte, so use mb_* functions for UTF-8 text.

Next: Integers and Floats