What is the difference between ' and " in PHP? [duplicate]
Possible Duplicate:
PHP: different quotes?
Simple question:
What is the difference between ' and " in php? When should I use either?
Solution 1:
Basically, single-quoted strings are plain text with virtually no special case whereas double-quoted strings have variable interpolation (e.g. echo "Hello $username";
) as well as escaped sequences such as "\n" (newline.)
You can learn more about strings in PHP's manual.
Solution 2:
There are 3 syntax used to declare strings, in PHP <= 5.2 :
- single quoted
- double quoted
- heredoc
With single quotes :
variables and escape sequences for special characters will not be expanded
For instance :
echo 'Variables do not $expand $either';
Will output :
Variables do not $expand $either
With double-quotes :
The most important feature of double-quoted strings is the fact that variable names will be expanded.
For instance :
$a = 10;
echo "a is $a";
Will output :
a is 10
And, with heredoc :
Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped,
For instance :
$a = 10;
$b = 'hello';
$str = <<<END_STR
a is $a
and "b" is $b.
END_STR;
echo $str;
Will get you :
a is 10
and "b" is hello.
Solution 3:
Any variables inside a " quoted string will be parsed. Any variables in a ' quoted string will not be parsed, and will be shown literally as the variable name. For this reason, ' quoted strings are very slightly faster for PHP to process.
$test = 'hello';
echo "this is a $test"; // returns this is a hello
echo 'this is a $test'; // returns this is a $test
I'd say use ' quotes unless you want variables inside your strings.
Solution 4:
The difference is, strings between double quotes (") are parsed for variable and escape sequence substitution. Strings in single quotes (') aren't.
So, using double quotes (") you can do:
$count = 3;
echo "The count is:\t$count";
which will produce
The count is:<tab>3
The same in single quotes returns the literal string.
Also, the characters that need to be escaped. If you have a string like:
'John said, "Hello"'
you would probably use single quotes, to avoid having to escape the quotes in the string and vice-versa.