What’s the difference between single & double quotes in PHP. This question is generally asked in interviews to check how well you understand the concepts. Also if you know the difference it will help you in your day to day programming.
In PHP you can specify the strings using four different ways single quotes , double quotes, heredoc and newdoc syntax. But most of the time single & double quotes is used to specify strings.
What’s the Difference Between Single & Double Quotes in PHP
Single Quotes
String enclosed in single quotes print as it is without being interpreted. It is faster and everything quoted inside treated as plain string.
How to prevent php script running out of memory.
Let’s check some examples.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php /* Declare variable blog and assigned string values. */ $blog = 'webrewrite.com'; /* Declare another variable and try to use previous variable value. */ $otherString = 'My blog is $blog'; echo $otherString; // Output : My blog is $blog /* If you want to print $blog value. Use .(dot) */ echo 'My blog is'.$blog; // My blog is webrewrite.com ?> |
Output – My blog is $blog
If i echo $otherString variable it will print the result as it is without being interpreted.
Exception – To display a literal single quote, you can escape it with a back slash \’, and to display a back slash, you can escape it with another backslash \\ (So yes, even single quoted strings are parsed).
Double Quotes
Let’s check the same example with double quotes.
1 2 3 4 5 6 7 8 |
<?php $blog = 'webrewrite.com'; echo "my blog name is $blog"; // Output: My blog name is webrewrite.com ?> |
output –
my blog name is webrewrite.com
In Double quote strings will be printed after interpretation. So it is better to use single quotes unless you need to interpret the variable value.
The advantage of using double quotes is you don’t need to use concatenation(.) operator for strings (Like ‘My blog is’.$blog).
Difference between double and triple equal to.
Is there any performance benefit of single quote compared to double quote in php ?
Yes single quote is slightly faster as it doesn’t interpret what is inside single quote. In case of double quotes, PHP has to parse and check if there any variable in there.
Reference – PHP Manual