dqzlqfqeh845799833 2012-11-02 16: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 17: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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度