PHP: single and double quotes
Tuesday / 19 April 05
I don’t write about PHP very often — this is the first time since the launch one year ago. However, I do quite a lot of work with PHP and relational databases such as MySQL. Almost every single time I review someone else’s work a common error related to using strings in PHP is made. Misunderstanding the way of defining strings in PHP is often the cause of many hours of debugging as well. If you are relatively new to programming and PHP you’ll most likely recognize this situation.
PHP lets you define strings using single quote, double quotes or heredoc. There’s a crucial difference between the first 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'
This possibly isn’t anything new to you, but 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 and vica versa. Using a double quote in a string enclosed in double quotes (idem for single quotes) does require escaping, which —in my opinion— degrades readability tremendously.
$text = 'Lorem Ipsum';
$uri = 'http://www.lipsum.com';
echo '<a href="' . $uri . '">' . $text . '</a>';
echo "<a href=\"$uri\">$text</a>";
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.

1Dom posted:
19 April 05, 14:16:37 PM
That last example, with the link - why would you do this instead of just type it in normally?
Thank you for this article, it has helped me improve my knowledge somewhat, but PHP is all still a blur :)
Ah well, one step at a time. Let me master XHTML/CSS first :)
Take care, Dominic