Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    WA
    WA is offline
    Administrator
    Join Date
    Mar 2002
    Posts
    2,596
    Thanks
    2
    Thanked 19 Times in 18 Posts

    Question regarding ternary operator

    Hi:
    Is it possible to use more than 2 expressions in a ternary operator in PHP? Apparently the below, with 3 expressions, doesn't work when I tried it:

    PHP Code:
    $inputpass=isset($test)? $test : isset($test2)? $test2 ""
    In JavaScript, the same concept works, so I'm curious why it doesn't in PHP. Basically the logic is to set $inputpass to three different values, depending on whether $test or $test2 is defined.

    Thanks,
    - George
    - JavaScript Kit- JavaScript tutorials and 400+ scripts!
    - JavaScript Reference- JavaScript reference you can relate to.

  • #2
    jkd
    jkd is offline
    Senior Coder jkd's Avatar
    Join Date
    May 2002
    Location
    metro DC
    Posts
    3,163
    Thanks
    1
    Thanked 18 Times in 18 Posts
    Perhaps you should use parentheses?

    There might be a different precedence of this operator in PHP than in JS:

    $inputpass = isset($test)? $test : (isset($test2)? $test2 : "");

    Also, in Javascript, you could achieve the same like so:

    inputpass = test || test2 || '';

    You might be able to utilize short-circuit validation in this case too if PHP treats undefined variables (I'm assuming that's what isset checks) as boolean false when typecasted.

  • #3
    Senior Coder
    Join Date
    Jun 2002
    Location
    frankfurt, german banana republic
    Posts
    1,848
    Thanks
    0
    Thanked 0 Times in 0 Posts
    jdk hit the nail on the head. Though I'm not quite sure if it's really the precedence of the operators, because this code

    PHP Code:
    $test1 "test1";
    $test2 "test2";

    $inputpass = isset($test1) ? ($test1) : isset($test2) ? $test2 "default";
    echo 
    $inputpass
    prints "test2", and I've expected "test1". Seems to be rather a weirdness of the expression evaluation, since it looks like the innermost ternary operator construct is evaluated first... hmh, I'm not quite satisfied with this explanation, because adding parentheses like jkd suggested solves that problem... strange indeed.

    P.S: I couldn't get that JS code to work if both tested variables did not exist (I got an "test is undefined" error). It worked ok with this adjustment:

    Code:
    inputpass = window.test1 || window.test2 || "default";


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •