Search
Close this search box.
Search
Close this search box.

Single Quotes vs Double Quotes

PHP lets you define strings using single quote or double quotes. There’s a crucial difference between these two and for some reason many people new to PHP start using double quotes. Hopefully the following explanation will save a couple of hours debugging for the starters among us.

The most important difference between the two is that a string enclosed in double quotes is parsed by PHP. This means that any variable in it will be expanded.

echo $var; // Results in the value of $var being printed
echo '$var'; // Results in the word '$var'
echo "$var"; // Results in the value of $var being printed

This means that concatenating strings can be done in two different ways as well.

$var = 'Ipsum';
echo 'Lorem ' . $var; // Results in 'Lorem Ipsum'
echo "Lorem $var"; // Results in 'Loren Ipsum'

Working with HTML

If you are working with HTML you can output valid markup while keeping your code readable. Using double quotes in a string enclosed with single quotes requires no escaping. Using a double quote in a string enclosed in double quotes does require escaping, which degrades readability tremendously.

$text = 'Lorem Ipsum';
$uri = 'http://www.lipsum.com';
echo '<a href="' . $uri . '">' . $text . '</a>'; // no escaping needed, just a dot
echo "<a href="$uri">$text</a>"; // needs escaping

Personally, I always stick to using single quotes and the dot syntax to concatenate strings, unless I need special characters such as new lines. Whatever you use is up to you, but hopefully this heads-up cleared a lot of confusion and puts an end to unreadible code and markup using single quotes.