Thursday, 4 October 2012

Difference between single and double quotes in PHP

Well first of all, single quotes are much more efficient than double quotes, which is shown in the results from a simple test, which you can find here:

So, there obviously is a difference between them, but what is it?

Simply put, single quotes are completely static, where as double quotes are dynamic with changing values.
For example:
$someVar = 'more Text';
echo 'Some Text $someVar';

will output
Some Text $someVar

However, the same example but with double quotes:
$someVar = 'more Text';
echo "Some Text $someVar";

will output
Some Text more Text

Obviously single quotes will have a better efficiency than double quotes, because in single quotes, php does not process anything within it, where as with double quotes, php is constantly looking through the string for variable names to check and call.

So how do we use this new knowledge to our advantage?

Well, since single quotes do not process variables how do we add variables to the string?
Well if you haven't figured it out, we simply use the string addition character.
For example:
$str = 'more text';
echo 'some text and '.$str;

It is a bit of a hassle, but like in most things about programming, its usually efficiency vs programing time. A classic example of this is, C++ vs C#.

However, when using single quotes, depending on your php version, '\n' will output \n, so you will occasionally have to use, "\n" or PHP_EOL

well, if you still want to use double quotes, because your lazy :D
there are still times when you may find it easier to use single quotes. for example, if you are outputting static text like HTML that has mass amounts of double quotes in it. Or if you want to output the name of a variable.

Of course, you could still do
echo "$"."varname";

instead of
echo '$varname';

but in that case you might as well just use single quotes.

So yes, there is a huge difference between the single and double quotes other than simple quote escaping.

Well, i hope this helps you a lot, and it is best to try to be as efficient as possible, ESPECIALLY when using loops. so its alright to use double quotes when your lazy, but be sure to avoid them when writing large loops, or commonly used functions.


No comments:

Post a Comment

Please post any queries and comments here.