RSS Feed

Know when to use double quotes

PHP is a great server side language to get into however more often than not developers are not aware of performance issues in their code. One issue is the use of double quotes for all string variables.

While this is OK in principle it’s worth remembering double quotes take longer to process than single quotes – so use single quotes when double quotes are not needed.

How do you know when double quotes are not needed? When a string does not contain 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.

So from today, use single quotes unless double quotes are needed. It’s good practice.

Posted in PHP on the 11th April 2010

4 people have spoken their minds!

  1. BaridBelMedar says:

    Very interesting, that I did not know…

  2. JaTaMan says:

    True SRCNIX. Recently, I have a case one of my colleague had problem with ‘\n’ and “\n”. He completly didn’t see the differece and couldn’t resovle his problem. Sometimes is good to remind basics.

    • srcnix says:

      It may be worth pointing your colleague over to this blog post then and possibly have a sit down with him and run over the basics. Do remember that people have off days so don’t go calling him an “idiot” or “fool”.


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