Single quotes vs Double quotes in PHP
One of the eternal debates in PHP is whether is best to use single quotes or double quotes to define a string. Here I will try to explain the basic pros/cons of each one.
Strings with double quotes
PROS
CONS
- You cannot write a text string which includes double quotes without using the escape slash. Let me explain. Since you have to start your string with a double quote, you cannot write another double quote inside the string; that would cause the valid string to close.
Example.
<?php
echo "My friends call me "The Party Monster" all the time";
$site = "google.com";
echo "<a href="http://$site/">Click here</a>";
?>
In the last example, both echo lines will cause PHP errors. In the first one I "accidentally" closed the string with the first quote of "Party Monster" and everything else is left outside the valid string. In the second line I closed my string before the URL even began so, again, everything else is left outside the string.
The workaround to include valid double quotes inside double-quoted strings is to use the escape slash. The escape slash is a (\) symbol which indicates PHP that the character right next to it should be taken as a special character.
So, the proper way to write the last example using double quotes would be:
<?php
echo "My friends call me \"The Party Monster\" all the time";
$site = "google.com";
echo "<a href=\"http://$site/\">Click here</a>";
?>
Now the echo lines will render properly, without errors.
At first, this issue doesn't seem to be such a big deal, but when you have to code a big web site full of HTML parameters enclosed in double quotes, the task can be quite annoying.
- PHP takes longer to process double quoted strings. Since the PHP parser has to read the whole string in advance to detect any variable inside—and concatenate it—it takes longer to process than a single quoted string.
This can be negligible for small sites with a few short strings; but if you need to process a big web site, with heavy loads of traffic and large strings to parse, the resources of your server can be significantly decimated.
Strings with single quotes
PROS
Cons
- Some people complain about the dot notation being too elaborated; personally I prefer it over the escape slashes every time I want to include HTML parameters in my strings—something I do a lot.
|
|