PHP – What is the difference between single and double quotes?

Difference between single and double quotes in PHP can be confusing. Moreover, it can lead to unexpected results, so it’s better to get familiar with it so you can avoid bugs.

Let’s dive into the details…

Quotes are used for representing strings in code, and you can use single or double quotes to do this. What you cannot do is to mix quotes, for example, to start with a double quote and end with a single quote.

Some people will argue that single quotes are faster because they are not parsed but they are. If you want to stuff single quote in the string you will need to escape it like this:

$some_string = 'This is \'single quote\' escaping example';

So the speed argument is really quite irrelevant. Even thou single quotes are a bit faster than double quotes the difference in speed shouldn’t be much of concern.

Double quotes will interpret a wider variety of characters including special characters, variables, regexes, arrays, objects.

$escape_char_example = "This is linefeed.\n";
$variable_example = "This is $variable example";
$array_example = "This is array: $some_array[0]";

There’s one important caveat with variable names inside of the double-quoted strings which need to be addressed. If the variable name is not separated with white space parser will use the whole word as a variable name until the first whitespace, which might not be what you wanted.

For example, if you want  to add suffix “man” to the value of the variable you need to use curly braces like this:

$name = "Jason";
// this won't work as expected - parser will look for $nameman variable
echo "$name becomes $nameman";
// this is right way
echo "$name becomes {$name}man";

Leave a Reply

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