Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

{PHP} Concatenating immediate if's

Options
  • 05-07-2008 3:45pm
    #1
    Registered Users Posts: 4,475 ✭✭✭


    Came across a strange issue today that took me far too long to debug. I had a line like this:
    echo "hello " . ($p_gender=="f")?"Mrs ":"Mr " . "Doyle";
    
    The code just wouldn't execute, no errors or anything just a blank space where I was expecting my output. I finally recoded it as
    echo "hello ";
    echo ($p_gender=="f")?"Mrs ":"Mr ";
    echo "Doyle"
    
    which just seems wasteful to me ;) Is this a known issue? Is there a better way of writing the first piece of code to work?


Comments

  • Registered Users Posts: 568 ✭✭✭phil


    Fix:
    echo "hello " . (($p_gender == "f") ? "Mrs " : "Mr ") . "Doyle";
    

    Always group operations and operators with parantheses, if for no other reason than code readability. However, the next best reason is what you've found out - introducing unintended bugs.

    Operator evaluation and precedence can sometimes be non-obvious. Make it obvious by grouping.

    FYI, the '?:' operator is called the ternary operator.


  • Registered Users Posts: 4,475 ✭✭✭corblimey


    phil wrote: »
    Fix:
    echo "hello " . (($p_gender == "f") ? "Mrs " : "Mr ") . "Doyle";
    

    Always group operations and operators with parantheses, if for no other reason than code readability. However, the next best reason is what you've found out - introducing unintended bugs.

    Operator evaluation and precedence can sometimes be non-obvious. Make it obvious by grouping.

    FYI, the '?:' operator is called the ternary operator.

    Thanks, phil. Very helpful (on both counts)


Advertisement