PHP lets you write a string with single quotes ('...') or double quotes ("..."). They look similar, but they behave differently.
Single quotes: exactly what you type
Single quotes keep the text as it is. No variables are replaced, and almost no escape codes work.
<?php
$name = "Maya";
echo 'Hello, $name\n';
Hello, $name\n
Double quotes: variables and escape codes work
Double quotes put the value of a variable into the text and understand codes like \n (new line) and \t (tab).
<?php
$name = "Maya";
echo "Hello, $name\n";
echo "Name:\tMaya";
Hello, Maya
Name: Maya
Escape codes in double quotes
| Code | Meaning |
|---|---|
\n | New line |
\t | Tab |
\" | A double quote |
\\ | A backslash |
\$ | A dollar sign (stops variable replacement) |
<?php
echo "She said \"hello\"\n";
echo "Cost: \$5\n";
echo "Folder: C:\\xampp";
She said "hello"
Cost: $5
Folder: C:\xampp
Escaping in single quotes
In single quotes you only need to escape two things: the single quote \' and the backslash \\.
<?php
echo 'It\'s a path: C:\\xampp';
It's a path: C:\xampp
Which one should you use?
- Use single quotes for plain text without variables. It is clear to the reader that nothing special happens.
- Use double quotes when you need a variable inside the text or an escape code.
Either choice is fine. Pick one style for a project and keep it. The speed difference is not worth thinking about.
Quotes inside HTML
HTML attributes use double quotes, so single-quoted PHP strings keep the code readable.
<?php
$url = "/about";
echo '<a href="' . $url . '">About</a>';
<a href="/about">About</a>
Single quotes in the wrong place
echo 'Total: $total'; prints the dollar sign and the word $total. If you expect the value, use double quotes.