1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Single Quotes and Double Quotes are very different in PHP

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

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    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:
    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:

    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:

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

    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:

    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:

    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.
     

Share This Page