If there’s one question that stumps new PHP programmers is the age old question: do I use single quotes or double quotes with my string? For example:
echo 'Hello, world!';
is exactly the same as
echo "Hello, world!";
But what is the actual difference? Well, it turns out that there are reasons why you might want to use one over the other. Single quotes are known as literal strings. This means whatever you put in them is literally processed as is. So for example, let’s look at the following code:
<?php $cookies = 5; echo "I have $cookies cookies."; echo 'I have $cookies cookies.';
Here’s what this code will output:
You can see that the double quotes processed the variable where as the single quotes ignored the variable and literally printed it. When you use single quotes, you can actually save some CPU, RAM, and speed in your scripts as PHP doesn’t think about processing it.
Escaping quotes
If you need to actually print out either single or double quotes in your statements, such as when outputting HTML, then you’ll need to escape the characters being used. Here’s how this works:
<?php echo "<a href=\"https://www.thelinuxlab.org\" target=\"_blank\">The Linux Lab</a>";
Notice that before the double quotes in the HTML, they were proceeded by a \
. The \
is an escape character. This tells PHP to ignore the quote and process it as part of the string. When you use a single quote and use single quotes in your string, they also need to be escaped.
<?php echo 'And my favorite movie is \'Gone With the Wind\' and I watched it on Saturday.';
And you can also mix single quotes and double quotes without escaping them. Take a look at these examples:
<?php echo "And my favorite movie is 'Gone With the Wind' and I watched it on Saturday.'; echo 'Our website is <a href="https://thelinuxlab.org">The Linux Lab</a>';
I hope you learned a little bit more about PHP and strings!