Ads 468x60px

Thursday, 18 April 2013

PHP - Single Quotes vs Double Quotes

PHP - Single Quotes vs Double Quotes

You may ore may not have even thought about this up to this point in your PHP use but it is kind of a big deal. Using the right or wrong quotes can not only cause errors that might be hard to find but there can be a slight performance boost and can make your code much easier to read.



     
1<?php
2     echo 'hello world';
3?>
_______________________________________

1<?php
2     echo "hello world";
3?>

These will produce the exact same end result but do you know which one is technically better? The single quote. The single quote just puts exactly what is inside of it without processing while the double quote actually evaluates and processes. Let me explain with an example.

1<?php
2 
3      $example 'hello world';
4 
5      echo '$example'// outcome will be $example
6 
7      echo "$example"// outcome will be hello world
8?>


As you can see here the double quotes take the time to process what is inside so technically there will be a little more overhead. Obviously on a small scale this means nothing but if you have a loop that iterates 1000 times you might start to see the benefits of single quotes in a performance sense.
Now if you are trying to put a variable in a sentence you can do this:
1<?php
2 
3    $example 'hello world';
4 
5    echo 'This is my '.$example.' for PHP';  // outcome This is my hello world for PHP
6    echo "This is my $example for PHP";  // outcome This is my hello world for PHP
7?>

Either of these will work just the same in getting the output that you want but the single quote will be slightly faster because while both have to process the variable the double quote is also scanning the rest of the sentence in search for anything that it has to process. Yes it is more typing but I personally find the first one much more readable because you can much more clearly see that you are outputing a variable. If this was randomly in a 500 line PHP file the single quote method would be easier to spot.


i am waiting for your comments ....


















0 comments:

Post a Comment

Most Wanted Posts

Related Posts Plugin for WordPress, Blogger...