Ternary operator

Discussion in 'PHP' started by OWL_on_NG, Jan 3, 2007.

  1. #1
    I've just started learning PHP yesterday, and in reading the PHP manual from php.net, I came across the Ternary operator. I found it very confusing and their definition lacking; could anyone do me the favor of explaining it in a little more detail.
    Thank you.
     
    OWL_on_NG, Jan 3, 2007 IP
  2. TwistMyArm

    TwistMyArm Peon

    Messages:
    931
    Likes Received:
    44
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Essentially the ternary operator provides a 'simpler' if / else.

    So:
    $a = ( $b ? $c : $d );

    translates to:
    if ( $b ) {
    $a = $c;
    } else {
    $a = $d;
    }

    Basically if the value before the question mark is true, set the value on the left hand side of the equal sign to whatever is between the question mark and the colon, otherwise set it to whatever is after the colon.

    $b can be anything that can be used as a boolean and $c and $d can be anything that could normally set a value to the left of an equal sign, so you can do some nifty things like calling functions depending on the true / false value of another function and so on.
     
    TwistMyArm, Jan 3, 2007 IP
    OWL_on_NG likes this.
  3. infernaliuns

    infernaliuns Active Member

    Messages:
    121
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    55
    #3
    More examples:

    
    <?
    
    //Validating a password:
    
    $username = "user123";
    $password = "123456";
    
    echo ($username == "user123" && $password == "123456") ? "Valid" : "Invalid";
    
    ?>
    
    PHP:
     
    infernaliuns, Jan 3, 2007 IP
    OWL_on_NG likes this.
  4. OWL_on_NG

    OWL_on_NG Active Member

    Messages:
    21
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    86
    #4
    Thanks a lot! :)
     
    OWL_on_NG, Jan 3, 2007 IP