dshdb64088 2014-09-09 21:52
浏览 292
已采纳

嵌套三元运算符的优先顺序

I was in class the other day and this snippet of code was presented:

 <?php
 //Intialize the input
 $score=rand(50,100);
 //Determine the Grade
 $grade=($score>=90)?'A':(
 ($score>=80)?'B':(
 ($score>=70)?'C':(
 ($score>=60)?'D':'F')));
 //Output the Results
 echo "<h1>A score of $score = $grade</h1>";
 ?>

At the time I questioned the order of operations within the nested ternary operators, thinking that they would evaluate from the inside out, that is it would evaluate if $score were >= 60 first, then if $score >= 70, etc -- working through the whole stack every time regardless of the score.

To me it seems that this construct should follow the same order of precedence given to mathematical operators -- resolving the inner-most set of parentheses first and then working out, unless there is some order of operations unique to the ternary.

Unfortunately the discussion in class quickly became about winning an argument, when I really just wanted to understand how it works. So my questions are two:

(1)How would this statement me interpreted and why?

and

(2)Is the some sort of stack trace or step through tool that would allow me to watch how this code executes?

  • 写回答

4条回答 默认 最新

  • dongwo5110 2014-09-09 22:09
    关注

    PHP respects brackets. Expressions inside the innermost ( ... ) are evaluated first, like we are taught in elementary school.

    PHP is unusual in that ternary operators are left-associative. This means without brackets, the ternary expression is evaluated left to right.

    But in this particular case, the brackets force the expression to be evaluated right to left. This code is equivalent to:

    if ($score >= 90) {
        $grade = 'A';
    }
    elseif ($score >= 80) {
        $grade = 'B';
    }
    elseif ($score >= 70) {
        $grade = 'C';
    }
    ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3