Escape sequences
Learn how to write special characters inside strings with \n, \t, \\ and \".
Escape sequences in double quotes
In PHP, certain sequences inside a double-quoted string have a special meaning: \n is a newline, \t is a tab, \\ is a backslash, \" is a double quote. These are called escape sequences.
For example, echo "Line1\nLine2"; prints two lines. If you want a double quote inside a double-quoted string, you must write \"; otherwise the string closes early. In single quotes only \\ and \' work; sequences like \n are treated as plain text.
Single quotes have limited escapes
Inside a single-quoted string, only two escapes work: \\ (backslash) and \' (single quote). Sequences like \n, \t, \" are treated as plain text in single quotes; they appear on screen exactly as typed.
That is why 'Line1\nLine2' shows the \n characters on screen. To get a real newline, use double quotes. Single quotes are preferred for fixed file paths because no backslash escaping is needed.
Exercise Print two lines with \n
Assign "First line" to $line1. Assign "Second line" to $line2. Then print them on two lines with echo $line1 . "\n" . $line2;.
Show example solution
Assign both strings, then join them with \n.
Example solution:
<?php
$line1 = "First line";
$line2 = "Second line";
echo $line1 . "\n" . $line2;
Test yourself
-
What does echo "A\nB"; print?
echo "A\nB";- Two lines: A and B
- AnB
- A B
- A\nB
Show answer
Two lines: A and B — Correct. \n is a newline; A and B appear on separate lines.
-
Escape a double quote
$msg = "Alex said: ____Hi";Show answer
$msg = "Alex said: \"Hi"; -
Match each escape sequence to its effect
- \n
- Newline
- \t
- Tab
- \\
- Backslash
- \"
- Double quote