David's Coding Blog

PHP - Single or double quoted string

While working on my PHP interpreter implementation, I learned some interesting differences between single and double quoted strings in PHP.
Some programming languages like Go make a distinction between a string (in double quotes) and a character (in single quotes). In PHP, both can be used, but depending on the type of string, different characters are escaped.

The similarities

Both types of string support the escaping (\) of the backslash and the associated quotation mark.


<?= "A quotation mark: \" and a baskslash: \\" ?>
// Output:
// A quotation mark: " and a baskslash: \

<?= 'A quotation mark: \' and a baskslash: \\' ?>
// Output:
// A quotation mark: ' and a baskslash: \

The difference

A difference can be seen in the usage of special characters such as carriage returns, line feeds or tags. Only the double quoted string prints them as special characters, while the single quoted string prints them escaped.


<?= "Tab: \t. Line feed: \n. Line feed with carriage return: \r\nFin" ?>
// Output:
// Tab: 	. Line feed: 
// . Line feed with carriage return: 
// Fin

<?= 'Tab: \t. Line feed: \n. Line feed with carriage return: \r\nFin' ?>
// Output:
// Tab: \t. Line feed: \n. Line feed with carriage return: \r\nFin

A feature that only the double quoted string supports is the variable substitution.
PHP searches the given double quoted string for variables and replaces them with the value. As you can see in the examples below, if a variable is not set, it prints an empty string.


<?php $var = 42; echo "Some{$var}iable" ?>
// Output:
// Some42iable

<?php $var = 42; echo "Some $var iable" ?>
// Output:
// Some 42 iable

<?php $var = 42; echo "Some $variable" ?>
// Output:
// Some