Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

{PHP} Concatenating immediate if's

  • 05-07-2008 03:45PM
    #1
    Registered Users, Registered Users 2 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, Registered Users 2 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, Registered Users 2 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