Go4Expert

Go4Expert (http://www.go4expert.com/)
-   PHP (http://www.go4expert.com/articles/php-tutorials/)
-   -   Single Quotes and Double Quotes are very different in PHP (http://www.go4expert.com/articles/single-quotes-double-quotes-php-t822/)

pradeep 22May2006 18:59

Single Quotes and Double Quotes are very different in PHP
 
I never recommend using " (double quotes) when programming with PHP. Always use ' (single quotes) unless you need the features of " (double quotes). You might think it's much easier to write code as:
Code: php

echo "Today is the $day of $month";


However, using single quotes forces variables to be outside the quotes; instead, you must use theperiod (.) to combine strings. It makes for faster coding but can be more difficult for other programmers to read. Let's look at what would happen if we put an associative array value in the previous code:

Code: php

echo "Today is the $date[?day?] of $date[?month?]";


You would receive a parse error and it would be harder for another team member to read. Two correct ways to write that line of code would be:

Code: php

echo 'Today is the ' . $date[?day?] ' of ' . $date['month'];


and

Code: php

echo "Today is the {$date['day']} of {$date['month']}";


These might not look as pretty as the original code, but syntactically they are both correct. Additionally, I believe the first method, with single quotes, is easier to read.

The use of single and double quotes also applies to associative arrays. Consider this code:

Code: php

$SESSION[team] = $SESSION["old_team"];


One main problem exists in that line of code. The associative entry team on the left side needs to have single quotes around it; otherwise, PHP will think it's a define and give you a warning message (only if error reporting is at maximum). I would recommend that the code should look like this:

Code: php

$SESSION['team'] = $SESSION['old_team'];


I wish I'd known the difference between single and double quotes as they pertain to strings when I first learned PHP.


All times are GMT +5.5. The time now is 02:57.