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条)

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行