When to use single quotes and double quotes

If you are familiar with PHP you will know that strings can be contained within single quotes or double quotes. More often than not developers tend to always use double quotes, despite the context of the string.

While this is OK in principle, double quotes take more processing time than that of single quotes (despite being minimal). This is because PHP expects to find variables within double quoted strings and parse them.

How do you know when to use single quotes over double quotes?

When a string doesn’t contain any variables. By using double quotes PHP will parse the string with the intention of evaluating variables whereas single quotes are literal, what you see is what you get.

A valid use of double quotes:

$name = 'Steve Clarke';
$string = "My name is $name";
echo $string;
// Outputs "My name is Steve Clarke"

An invalid use of double quotes

$string = "My name is Steve Clarke";

The above should use single quotes

$string = 'My name is Steve Clarke';

This practice is pretty simple and extremely easy to implement in your future programming sessions. Just keep in mind that performance is always an issue and every little helps.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>