Single Quotes and Double Quotes in PHP
PHP lets developers output strings to the screen using single or double quotation:
print ‘Hello world’; print “Hello world”;
Both of these statements product the exact same output to the screen in terms of what the browser sees. However, these is a distinct difference in how PHP handles these statements.
The first statement uses single quotes as delimiters to the string. PHP interprets this as a string to directly output to the page with minimal processing. The second statement uses double quotes as delimiters. The difference in the way PHP handles this is that before outputting to the page, PHP will scan the entire string looking for variable names that it could substitute into the final string. For example:
// store todays date to a variable $today = date(’d/m/y’); // print the sentence wrapped in single quotes print ‘The date is $today’;
The output of this short piece of code would be:
“The date is $today”
Because of the single quotes wrapped around the string, PHP has skipped any variable interpretations within the string, and has outputting exactly what was put in. This saves processing time in PHP which, although minimal, could result in large savings on processing time and memory on a large scale website.
We can update our code to wrap the string in double quotes, as such:
// print a sentence, with todays date using double quotes print “The date is $today”;
The output of this code will be:
“The date is 09/02/07″
This time, PHP has parsed the string prior to output and found what looks to be a variable name it has a value for - ‘$today’. It has then substituted the variable name in the string, for the value the variable currently holds.
A further approach to this is to use concatonation to take advantage of the quicker single quotation method, but to also glue variables into the same print statement and have them work as you’d expect:
// print todays date print ‘The date is ‘.$today;
The part of the sentence that always stays the same is wrapped in single quotes, and is joined to the variable using a fullstop. This means that the variable is completely outside of any quotation, and is handled by PHP exactly as it would be anywhere else in the code, giving the output:
“The date is 09/02/07″
Although a very simple issue, quotation issues in PHP can be unexpected pitfalls for programmers. Although I was taught PHP to use double quotes around everything, and variables being included in strings/function calls as I would expect, by opting to be a little careful and using single quotes where necessary can contribute to taking some of the load off your server!
















Excellent Explanation I like it and i appreciate your effort