Tuesday 29 January 2013

When to use double quotes and single quotes in php ?

The answer is really simple , if you want to put something in a sentence exactly the way it is , use single string , if u want php to do some processing (identifying the variables etc.) use double quotes . Using single quotes you want be able to reference a variable inside it since php will treat the entire stuff in between the single quotes as a string . But it is not so in case of double quotes !! In case of double quotes php will actually do some processing on it's own and see whether any variables are present inside it and will replace them with their values . Consider the following example :-


$var = "Sample Text !!";
echo '$var';         //Outputs $var
echo "$var";       //Outputs Sample Text!!

?>

Now does that mean we should use double quotes always ? NO !! You must be wondering why ? Well , it's obvious that double quotes will require some more overhead since it does processing , so it will take some more time than single quotes . If there is a single line to be printed or so then this is not an issue , but suppose you have a loop that iterates a million times , what then ? It will be that extra time multiplied by a million !!

Suppose you have something inside the loop which is as follows :-

echo "Item Number :- $item";

Then write it as :-

echo 'Item Number :-'.$item;

In case of larger iterations this method should work more quickly than the previous one !!

No comments:

Post a Comment