Search code examples
phpoperator-keywordternary

Nested ternery operators output wierd result


This outputs 'Option 1'. I have no idea what is wrong with it.

$result = (0 == 0) ? 'Option 0' : (1==2) ? 'Option 1' : 'Option 2';

Thanks!


Solution

  • You have an issue with Operator Precedence and the Ternary Operator here. Your lack of understanding becomes visible where you place the parenthesis. Let's review:

    $result = (0 == 0) ? 'Option 0' : (1 == 2) ? 'Option 1' : 'Option 2';
              ^      ^                ^     ^
    

    I'm not saying it is easy, but as this code already shows, you have placed superfluous round brackets here. They are just not needed, this is often a sign of uncertainty with the own code. The correct variant would be:

    $result = 0 == 0 ? 'Option 0' : 1 == 2 ? 'Option 1' : 'Option 2';
    

    Now, this already shows that you are uncertain about where to place the parentheses. Knowing about this, also contains the solution to your problem. Turn your weakness into a strength by just doing the first check first and the second, second - but this time making actual use of parenthesis:

    $result = 0 == 0 ? 'Option 0' : (1 == 2 ? 'Option 1' : 'Option 2');
                                    ^                                ^
    

    This will give you your expected result, the parenthesis control precedence now as intended.


    Tip: You can make the decision tree more visible by using indentation when you write such statements:

    $result = 
        0 == 0 ? 'Option 0' 
               : (1 == 2 ? 'Option 1' 
                         : 'Option 2')
    ;
    

    (or similar) Just to make this more readable at first glance. As it shows this is a complex decision. As with complex things, errors in writing code for them occur more often. That is normal. Keeping the code readable by using indentation can help. Another way is to reduce the complexity.

    $decide  = 2:
    $results = array(
        0 => 'Option 0', 
        1 => 'Option 1',
    );
    $result  = isset($results[$decide]) ? $results[$decide] : 'Default Option';
    

    Here only one decision is needed, so it is less complex. This example makes more sense if you have more than three possibilities but even for three possibilities this can already be an improvement because it is visible right ahead that there is a default case.