Skip to content

PHP Tip: Use single quoted strings

by Vincent on April 8th, 2010

In PHP we have two different ways of defining strings and you should be aware of the difference between them.

Single quoted style.
$text = 'This is a small text.';
Double quoted style.
$text = "This is a small text.";

When using the single quoted style you force the string between the quote’s to be a ‘real’ string without any special characters or variables. By special characters I mean characters like new line breaks ‘\n’ or a carriage return ‘\r’ for example. Yes, special characters and variables are supported in the double quoted style, lets take a look at this example.

// Double quoted
$name = 'John';
$text = "Hello, $name";
echo $text; // Result: Hello, John

// Single quoted
$name = 'John';
$text = 'Hello, $name';
echo $text; // Result: Hello, $name

As you can see the single quoted style takes the string and won’t do any transformations on the data between the quote’s. The double qouted style finds a variable $name and copies its content into the string variable $text. But what if you want to use the variable $name and single quotes?

// Single quoted (working)
$name = 'John';
$text = 'Hello, ' . $name;
echo $text; // Result: Hello, John

I prefer the last way of working because of the following reasons. First of all it looks a lot cleaner to me and you will see that you’re strings are really strings with variables attached to it (dot means concat). And not some string with a variable hidden in it. For you and other developers it will be a lot easier to skim the PHP code and see where that variable is hidden. The other reason is performance. Using single quotes and concat is slightly faster than double quotes, as described here.

For more information about the string type in PHP you can read this page. On that page is also a list of ‘special/escaped characters’ which will not work as you may expect when using in single quoted strings.

From → PHP

2 Comments
  1. Frank Oosterhuis permalink

    When using multiple variables, I like to use sprintf.
    Like so:

    $var1 = ‘Frank’;
    $var2 = 25;

    $text = sprintf(‘My name is %s and I am %d years old’, $var1, var2);
    echo $text; // Result: My name is Frank and I am 25 years old

  2. Vincent permalink

    @Frank Oosterhuis
    The function sprintf is also a very good way of making text variables I do agree with that. It even has some nice features like type specifiers.That is why I think sprintf is perfect for advanced text formatting. But for simple formatting you probably be better of with some single quotes if you don’t need these advanced features. Thanks for sharing you’re point of view!

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS