Difference between single and double quotes in PHP



Today in this tutorial I will show you the difference between single and double quotes in PHP.

Strings within double quotes:

1. You can put variables directly within the text. The PHP parser will automatically detect such variables, convert their values into readable text and replace variables.

$var1 = "single";
$var2 = 'double';

echo "Difference between $var1 and $var2 quotes in PHP.";

Above example will render on screen:

Difference between single and double quotes in PHP.

The variables were automatically detected and concatenated with the text.

2. You can not write double quotes within double quotes without using the escape slash.

echo "The variables were automatically "detected and concatenated" with the text.";

Above example cause parse error because the first quote of “detected and concatenated” closed the string, and after this everything is invalid.

So to fix this problem we need to use escape slash to use double quote within double quote.

echo "The variables were automatically \"detected and concatenated\" with the text.";

3. Since PHP parser has to read full text in advance to detect any variable inside and concatenate it, it takes longer to process than a single quotes text.

Strings within single quotes
1. The text appears as it is. When you enclose a string with single quotes, PHP ignores all your variables. Plus, you are able to write double quotes inside the text without the need of the escape slash.

$name = 'Rahul';
echo 'Hi, my name is $name. I am a "developer"';

It will render like below:

Hi, my name is $name. I am a "developer"

2. Since PHP parser does not need to read the whole text in advance, the server can work faster with single quotes.

Difference:

1) The string or variables present within double quotes are evaluated, but if the string or variables present in single quotes it will just prints as it is.

2) All HTML tags will work in both single and double quotes.

3) It is not possible to use single quotes within a single quotes and double quotes within a double quotes. But we can use single quotes within double quotes and double quotes within single quotes.