Monday 2 February 2015

PHP double quotes vs single quotes

PHP double quotes vs single quotes


Strings in PHP can be specified in four different ways: single quoted, double quoted, heredoc syntax and (since PHP 5.3.0) nowdoc syntax, the first two of them being by far the most frequently used.
It is important to know the difference between using single quotes and double quotes. In this post we will see the difference between them and which should be used when.
Single quoted strings are the easiest way to specify string. This method in used when we want to the string to be exactly as it is written. When string is specified in single quotes PHP will not evaluate it or interpret escape characters except single quote with backslash (‘) and backslash(\) which has to be escaped.
1
2
echo 'This is \'test\' string';
//Output: This is 'test' string
In double quoted strings other escape sequences are interpreted as well any variable will be replaced by their value.
1
2
3
$count = 1;
echo "The count is $count";
//Output: The count is 1
If we use single quotes instead of double quotes for the above example it will be like this:
1
2
3
$count = 1;
echo 'The count is $count';
//Output: The count is $count
I recommend using single quotes (‘ ‘) for string unless we need the double quotes (” “). This is because double quotes forces PHP to evaluate the string (even though it might not be needed), whereas string between single quotes is not evaluated. Also, parsing variables between strings takes more memory than concatenation.
So instead of this:
1
2
$count = 1;
echo "The count is $count";
use this:
1
2
$count = 1;
echo 'The count is ' . $count;

0 comments:

Post a Comment