Both kinds of enclosed characters are strings. One type of quote is conveniently used to enclose the other type of quote. "'"
and '"'
. The biggest difference between the types of quotes is that enclosed identifier references are substituted for inside double quotes, but not inside single quotes.
Single quoted
The simplest way to specify a string is to enclose it in single quotes. Single quote is generally faster, and everything quoted inside treated as plain string.
Example:
echo 'Start with a simple string'; echo 'String\'s apostrophe'; echo 'String with a php variable'.$name;
Double quoted
Use double quotes in PHP to avoid having to use the period to separate code (Note: Use curly braces
{}
to include variables if you do not want to use concatenation (.
) operator) in string.
Example:
echo "Start with a simple string";
echo "String's apostrophe";
echo "String with a php variable {$name}";
Is there a performance benefit single quote vs double quote in PHP?
Yes. It is slightly faster to use single quotes.
PHP won't use additional processing to interpret what is inside the single quote. when you use double quotes PHP has to parse to check if there is any variables in there.
- Single quoted strings will display things almost completely "as is." Variables and most escape sequences will not be interpreted. Only exception is 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\\
- 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. For example let's say you have the variable
$type
and you what toecho "The $types are"
That will look for the variable$types
. To get around this useecho "The {$type}s are"
You can put the left brace before or after the dollar sign. Take a look at string parsing to see how to use array variables and such. - Heredoc string syntax 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) string syntax 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.
No Comment to " Single-quoted and double-quoted strings in PHP, finding difference "