dqzlqfqeh845799833 2012-11-02 08:47 采纳率: 0%
浏览 92
已采纳

嵌套的三元运算符输出奇怪的结果

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!

  • 写回答

5条回答 默认 最新

  • doujianjian2060 2012-11-02 09:05
    关注

    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.

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部