Single Quotes and Double Quotes are very different in PHP

Discussion in 'PHP' started by pradeep, May 22, 2006.

  1. pradeep

    pradeep Team Leader

    Apr 4, 2005
    Likes Received:
    Trophy Points:
    Kolkata, India
    Home Page:
    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:
     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:

    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:

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

    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:

    $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:

    $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.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice