Strings in PHP
A string in PHP is a series of bytes that usually holds text. You write one between single quotes, between double quotes, or as a heredoc or nowdoc block. Double quotes and heredoc replace a variable such as $name with its value, while single quotes and nowdoc keep the text as written.
Key facts
- Inside double quotes,
$nameis replaced by the variable's value. Inside single quotes, it stays as the five characters$name. - The dot operator
.joins strings. The+operator adds numbers instead, and"Ada" + "Lovelace"stops with a TypeError. strlen()counts bytes rather than characters.strlen("café")returns 5 because the é takes up two bytes in UTF-8.- Since PHP 7.3, the closing name of a heredoc can be indented, and PHP removes that indentation from every line of the text.
- In double quotes,
\xais an escape for a line feed. That's why"C:\xampp"printsC:and thenmppon a new line.
How do you create a string in PHP?
Write text between single quotes or double quotes to create a string in PHP. A string typed out in the code like this is called a string literal, and you can print it with echo or store it in a variable.
The two kinds of quotes treat a variable name differently. Double quotes replace $name with the value it holds, and single quotes print the dollar sign and the name as typed.
$name = "Ada";
echo "Double quotes: Hello, $name!\n";
echo 'Single quotes: Hello, $name!';Double quotes: Hello, Ada! Single quotes: Hello, $name!
Quotes are two of the four ways to write a string in PHP. The other two, heredoc and nowdoc, suit longer text that spans several lines. A heredoc works like double quotes, and a nowdoc is stricter than single quotes, with no escape sequences.
What is the difference between single and double quotes in PHP?
Double quotes replace variables with their values and process escape sequences, and single quotes don't. Inside single quotes, a backslash only matters before another single quote or a second backslash, and everything else prints as typed.
| What you want | Single quotes | Double quotes |
|---|---|---|
The value of a variable such as $name | Not possible, $name prints as typed | Write $name or {$name} |
| A line break or a tab | Type it into the string, because \n and \t print as typed | Write \n or \t |
| A single quote | Write \' | Type ' |
| A double quote | Type " | Write \" |
| A dollar sign before a letter or underscore | Type $ | Write \$ |
| A backslash | Write \\, or one \ where no ' or \ follows | Write \\, or one \ where no escape sequence starts |
An apostrophe in the text is one reason to pick double quotes. Double quotes take one with no backslash, while single quotes need \'.
echo "It's 5 o'clock.\n";
echo "It\'s 5 o\'clock.\n";
echo 'It\'s 5 o\'clock.';It's 5 o'clock. It\'s 5 o\'clock. It's 5 o'clock.
In double quotes, "It\'s" prints It\'s with the backslash, because \' isn't an escape sequence there. PHP keeps the backslash before any character that doesn't start one.
Single quotes don't make a string faster. Before the script runs, PHP compiles 'Hello' and "Hello" into the same stored value.
For line breaks in output, including PHP_EOL, see echo and print in PHP.
How do you put a variable inside a PHP string?
Type the variable straight into a double-quoted string, and PHP replaces it with its value. This is called string interpolation, and it works the same way in a heredoc.
$name = "Ada";
$days = 4;
echo "$name is away for $days days.\n";
echo "$name's desk is empty.";Ada is away for 4 days. Ada's desk is empty.
The number in $days turns into text as PHP builds the string. After a $, PHP reads the longest name it can from letters, digits and underscores, so a space, an apostrophe, a hyphen or a period ends the name.
Only variables are replaced. Math, constants and function calls stay as plain text, so "$a + $b" prints the two values with a plus sign between them. Build those strings with the dot operator instead.
A $ that can't start a variable name stays as it is, so "Only $5 today" prints Only $5 today. To print a dollar sign before a letter or underscore, write \$, as in "Use \$total", which prints Use $total.
When do you need curly braces in a PHP string?
Use curly braces when a letter, digit or underscore comes right after the variable name. Without braces, PHP reads those characters as part of the name and looks for a variable that doesn't exist.
$fruit = "apple";
echo "I ate two {$fruit}s.\n";
echo "I ate two $fruits.\n";I ate two apples. Warning: Undefined variable $fruits in /app/main.php on line 4 I ate two .
PHP reads "$fruits" as a variable named $fruits, prints an Undefined variable warning and leaves a gap where the value would go. The braces in "{$fruit}s" mark where the name ends.
The { has to touch the $. With a space, as in "{ $fruit}", PHP prints both braces as plain text around the value.
Braces also stop PHP from reading a [ after the name as part of the variable. With $name set to Ada, "$name[0]" prints A, the character at position 0, while "{$name}[0]" prints Ada[0].
Arrays, a topic for later in the course, need braces too when the key is in quotes, as in "{$user['name']}". Without the braces, that quoted key stops PHP with a parse error.
Older code sometimes puts the dollar sign outside the braces, as in "${fruit}". PHP 8.2 deprecated that form. It still runs in PHP 8.6 but prints a Deprecated notice, and it's planned for removal in PHP 9.0. Write "{$fruit}" instead.
How do you concatenate strings in PHP?
Join strings with a dot, ., which PHP calls the concatenation operator. The dot adds no space of its own, so put any space you need inside one of the strings.
$first = "Ada";
$last = "Lovelace";
echo $first . $last . "\n";
echo $first . " " . $last;AdaLovelace Ada Lovelace
Numbers turn into text when you join them. "Room " . 101 gives Room 101. The + operator doesn't join strings. It's one of PHP's arithmetic operators, and text such as "Ada" makes it stop with a TypeError.
Since PHP 8.0, + and - run before the dot, so "Room " . 100 + 1 also gives Room 101. Parentheses, as in "Room " . (100 + 1), make that order plain to anyone reading the code.
How do you add text to the end of a string in PHP?
Use .= to add text to the end of a string variable. PHP calls it the concatenating assignment operator, and $list .= "!" does the same as $list = $list . "!".
$list = "Milk";
$list .= ", eggs";
$list .= " and bread.";
echo $list;Milk, eggs and bread.
Give the variable a starting value first, even an empty string, "". A .= on a variable that doesn't exist yet still stores the text, but PHP prints an Undefined variable warning before it does.
Watch out for +=, which adds numbers the way + does. Writing $list += "!" stops with the same TypeError as +.
Which escape sequences work in PHP strings?
Escape sequences work in double-quoted strings and heredoc, and each one starts with a backslash. PHP turns it into the character it stands for.
| Sequence | What PHP puts in the string |
|---|---|
\n | A line feed, which starts a new line |
\r | A carriage return |
\t | A horizontal tab |
\v | A vertical tab |
\e | The escape character |
\f | A form feed |
\\ | One backslash |
\$ | A dollar sign that doesn't start a variable |
\" | A double quote |
\101 | The byte with that octal value, written with one to three digits from 0 to 7, so "\101" is A |
\x41 | The byte with that hexadecimal value, written with one or two digits, so "\x41" is A |
\u{e9} | The character with that hexadecimal Unicode number, so "\u{e9}" is é (the braces are required) |
A backslash before any other character stays in the string, as in "\q", which prints \q. In single quotes, only \' and \\ are escape sequences.
echo "She said \"hi\".\n";
echo "Total: \$total\n";
echo "Folder: C:\\xampp\\htdocs\n";
echo "Caf\u{e9}";She said "hi". Total: $total Folder: C:\xampp\htdocs Café
Why does a Windows path break in a double-quoted PHP string?
Backslashes in the path can start escape sequences. In "C:\xampp\htdocs", PHP reads \xa as a hexadecimal escape for a line feed, so the path splits over two lines.
echo "C:\xampp\htdocs\n";
echo 'C:\xampp\htdocs';C: mpp\htdocs C:\xampp\htdocs
Single quotes keep the path as typed, because \x means nothing there. In double quotes, double every backslash, as in "C:\\xampp\\htdocs". The same trap turns the \n in "C:\new" into a line break.
How do you write a multi-line string with heredoc or nowdoc in PHP?
Start a heredoc with <<< and a name, then end it with that name on a later line. Everything between those lines is one string that can hold quotes with no backslashes, and variables and most escape sequences work as they do in double quotes.
$title = "Strings in PHP";
$author = "Ada";
echo <<<HTML
<article class="post">
<h2>$title</h2>
<p>By $author</p>
</article>
HTML;<article class="post"> <h2>Strings in PHP</h2> <p>By Ada</p> </article>
The line break before the closing name doesn't belong to the string. The text ends right after </article>. One escape sequence works differently in a heredoc, where \" keeps its backslash.
A nowdoc puts the name in single quotes, as in <<<'TEXT'. Nothing inside it is replaced, not even \\ or \', which suits text full of dollar signs and backslashes.
$name = "Ada";
echo <<<'TEXT'
Hello, $name!
Backslashes stay too: \n \t
TEXT;Hello, $name! Backslashes stay too: \n \t
A heredoc or nowdoc name may use letters, digits and underscores, but it can't start with a digit. Pick a name that never starts a line of the text as a word of its own, because PHP ends the string at the first line that does.
How do you indent a heredoc in PHP?
Indent the closing name, and PHP removes that much indentation from every line. This has worked since PHP 7.3, and it lets a heredoc line up with the code around it.
$name = "Ada";
echo <<<HTML
<ul>
<li>$name</li>
</ul>
HTML;<ul> <li>Ada</li> </ul>
With the closing name four spaces in, PHP removes four spaces from each line, and the <li> line keeps its two extra spaces.
Apart from blank lines, no line of the text may be indented less than the closing name, and the indentation can't mix tabs and spaces. Either mistake is a parse error, which stops PHP before any of the script runs.
echo <<<TEXT
Hello
TEXT;Parse error: Invalid body indentation level (expecting an indentation level of at least 4) in /app/main.php on line 3
PHP 7.3 also lets code follow the closing name on the same line, as in TEXT . "!";. Older tutorials that say the closing name must start its line and be followed only by a semicolon describe the rules from before PHP 7.3.
How do you get the length of a string in PHP?
Call strlen() to get the length of a string in bytes. For text in ASCII, the basic set of English letters, digits and symbols, each character is one byte, so the length in bytes is also the number of characters.
$word = "café";
echo strlen("Hello") . "\n";
echo strlen($word) . "\n";
echo mb_strlen($word);5 5 4
PHP strings hold bytes and don't keep track of characters. In a file saved as UTF-8, the é in café takes two bytes, so strlen() counts five. var_dump() reports the same number, as string(5) "café".
mb_strlen() counts characters instead and returns 4. It comes from the mbstring extension. The runner has it loaded, but PHP doesn't enable it by default, so your own install may need it turned on.
Paste café into the character counter to see both numbers side by side, 4 characters and 5 bytes. strlen() is one of PHP's many built-in string functions, and a later lesson covers common ones such as str_replace() and substr().
How do you get one character from a PHP string?
Put the character's position in square brackets after the string, counting from 0. Negative positions count back from the end and work since PHP 7.1, so $word[-1] is the last character.
$word = "Hello";
echo $word[0] . "\n";
echo $word[1] . "\n";
echo $word[-1];H e o
Positions count bytes, like strlen(). $word[3] on "café" gives only the first of the two bytes in é. A position past the end prints an Uninitialized string offset warning.
Common mistakes with strings in PHP
A backslash, a dot or a pair of braces fixes each of these PHP string mistakes.
- Parse error: syntax error, unexpected identifier "s". An apostrophe ended a single-quoted string early, as in
'It's here'. Write\'for the apostrophe, or put the string in double quotes. - Fatal error: Uncaught TypeError: Unsupported operand types: string + string. The code joins text with
+or+=. Use.or.=instead. - Parse error: syntax error, unexpected variable "$name". A dot is missing between a string and a variable, as in
"Hello, " $name. Add the dot. - Warning: Undefined variable $fruits. Letters after a variable name inside a string became part of the name. Wrap the variable in braces, as in
"{$fruit}s".
Joining two names with + stops this script with the TypeError. With a dot in place of the +, it prints AdaLovelace.
$first = "Ada";
$last = "Lovelace";
echo $first + $last;
Fatal error: Uncaught TypeError: Unsupported operand types: string + string in /app/main.php:4
Stack trace:
#0 {main}
thrown in /app/main.php on line 4Exercise
Fix this script so echo $message; prints two lines, Hello, Ada! and then You have 3 new messages. Use $name and $count for the name and the number instead of typing them, and add the second line to $message with .=.
$name = "Ada";
$count = 3;
$message = 'Hello, $name!\n';
$message += "You have $count new messages.\n";
echo $message;
Hello, Ada! You have 3 new messages.
Show the solution
$name = "Ada";
$count = 3;
$message = "Hello, $name!\n";
$message .= "You have $count new messages.\n";
echo $message;
Quiz
This quiz has 5 questions. Pick an answer to see why it is right or wrong.
-
1What does this script print?
$name = "Ada"; echo 'Hi, $name';Single quotes print $name as typed, dollar sign included. Hi, Ada is what the same line prints with double quotes.
-
2What does this script print?
echo "5" . "5";The dot joins the two strings side by side and adds nothing between them. 10 is what + would print, because + adds strings that hold numbers.
-
3Which statement adds a period to the end of the string in $text?
The .= operator appends the right side to the variable, which is what $text = $text . "." would do. The += operator adds numbers and stops with a TypeError on text, and $text . "." builds the longer string without storing it.
-
4What number does this script print?
echo strlen("café");strlen() counts bytes, and in UTF-8 the é takes two of them, so the four letters add up to 5. The function that returns 4 is mb_strlen(), which counts characters.
-
5What does this script print?
$total = 3; echo <<<'TEXT' Total: $total TEXT;The single quotes around TEXT make this a nowdoc, which replaces nothing, so $total prints as typed. Without those quotes, the same heredoc would print Total: 3.























