Code Perfectionist - Part 2 - Quotes

I am doing this little mini-series of how I like to format my PHP code. 2 weeks ago, I spoke about spacing. This week is about quotes. This one is only a quick one.

In PHP, you can use single and double quote interchangeably (obviously in pairs, i.e. you can mix them for a single string). But they both have slightly different properties.

The main one is this scenario:

 $var = 2;
 echo 'I have $var oranges.';
 echo "I have $var oranges.";

The first statement will output:

I have $var oranges.

The second:

I have 2 oranges.

So with double quotes, you can do variable substitution without having to use string concatination. For this reason, using double quotes for a string causes parsing that string to be slightly slower than if you used single quotes, even if you do not use any variables.

So I would say, ALWAYS use single quotes unless you want to substitute a variable.

Array indexes such as $array['key'] should NEVER use double quotes. It just looks a lot cleaner with single quotes and if you have a lot of them together, I think it improves the readability of the keys.

One scenario is a little bit tricky:

 $string = 'My name is Antony D'Andrea';

This will cause syntax errors to appear because the apostophe in my name is treated as a single quote and is paired with the first one. This makes everything after it just become junk.

In this scenario, you have two options: escape the apostrophe or use double quotes.

 $escapedString = 'My name is Antony D\'Andrea';
 $doubleQuotes = "My name is Antony D'Andrea';

I think that in this scenario, use the double quotes for the sake of readability and reduction of mistakes caused with escaping characters.

Most importantantly be consistent. If you have a class, do not keep switching between single quotes and double quotes. Stick to one style or the other.


© 2012-2017