Single Quotes vs Double Quotes

Looks like someone’s got a case of the mondays!

If you’re used to writing HTML, you’re probably used to using double quotes all the time. If you’re used to Javascript you’re probably used to using double- and single-quotes interchangably. Both single quotes and double quotes can be used to contain strings but in PHP there is subtle difference between the two.

Single quotes are used for containing string literals i.e. it’s a string which literally stores what you see. Any variables and control characters (such as \n) inside of a doublequoted string are evaluated by PHP. For example:

$test = "This is a test.";
echo 'What is this? $test';
echo "What is this? $test";

The above code would display this result:

What is this? $test
What is this? This is a test.

As you can see, the single quoted string literally writes out what it contains. In the double quoted string the $test variable is evaluated.

However this doesn’t mean you can slap any old bit of code inside a double quoted string and let PHP sort it out. For example, this code:

echo "this is a test $_GET['indeed']";

will result in something like this:

Parse error: parse error, expecting `T_STRING' or `T_VARIABLE' or `T_NUM_STRING' in test.php on line 1

You might now be wondering which one is better in terms of optimisation and resource use. Consider the following:

echo 'test' . $var;
echo "test $var";

Both lines effectively do the same thing (actually theres an extra space in the second line for legibility but shhh!) however the top line will run ever so slightly faster. For the above example the difference would be so minute that you could blink and miss a few thousand of them. When you’re making pages that are served to millions of people daily then that difference can be magnified to something noticable.

One more thing that double quotes can do:

$strings = "can be put accross
multiple lines of code,
without causing an error.";

So, the bottom line: it’s good practice to use single quotes as much as possible. There are times when double quotes are useful but single quotes are generally the way to go.


About Mr Chimp

I make music, draw pictures, browse the internet, programme, and make sweet, sweet cups of tea until the early hours.
This entry was posted in Programming and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s