Single vs double quotes in PHP

PHP Strings

Single quoted strings

  • Will display things almost completely as is.

  • Variables and most escape sequences will not be interpreted.

  • The exception is that to display a literal single quote, you can escape it with a back slash \',and to display a back slash, you can escape it with another backslash \\.

Example:

echo '$variable';

Output:

$variable

Double quote strings

  • Will display a host of escaped characters (including some regexes), and variables in the strings will be evaluated.

  • An important point here is that you can use curly braces to isolate the name of the variable you want evaluated.

Example:

$variable = 10;

echo $variable;

Output:

10

Heredoc

  • Works like double quoted strings.

  • It starts with <<<.

  • After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.

  • You don’t need to escape quotes in this syntax.

Nowdoc (since PHP 5.3.0)

  • Works essentially like single quoted strings.

  • The difference is that not even single quotes or backslashes have to be escaped.

  • A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'. No parsing is done in nowdoc.

Credit

GitHub OctocatFound a typo? Something wrong with this content? Just fork and edit it.

Content of this work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license. Code snippets in examples are published under the CC0 1.0 Universal (CC0 1.0). Thanks to all the contributors.