PHP single vs double quotes explained

Posted on Oct 04, 2022

Learn the differences between using single and double quotes in PHP

Photo from Unsplash

PHP allows you to use either single or double quotes when defining a string.

But there’s a difference when you use single quotes instead of double.

The main difference is that strings in double quotes are processed (or evaluated) while single quote strings are treated as they are.

When using double quotes, you can put variables and escape sequences in the string as follows:

<?php
$word = "morning";

print "good $word!";

print "\r\nThe weather is good today.";

The output will be:

good morning!
The weather is good today.

When you use single quotes, then you can’t put a string directly as shown below:

<?php
$word = 'morning';

print 'good $word!';

print '\r\nThe weather is good today.';

The output is as follows:

good $word!\r\nThe weather is good today.

As you can see, both the variable and the escape sequences are interpreted as it is.

PHP doesn’t process any special characters in a string enclosed with single quotes.

When you use double quotes, you can also use curly braces ({}) to isolate the variable name for evaluation.

Suppose you want to join two variables using an underscore (_). You can enclose the variables using curly braces as follows:

<?php
$first_name = "Nathan";
$last_name = "Sebhastian";

$full_name = "{$first_name}_{$last_name}";

Without the curly braces, PHP will look for the $first_name_$last_name variable.

Aside from enclosing a variable, the curly braces also make the variables inside the string more standout. Sometimes you can mistake a variable for a regular string without the curly braces.

And now you’ve learned the differences between single and double quotes when defining a string. Good work! 👍

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.