dshdb64088 2014-09-09 13: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 14: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条)
编辑
预览

报告相同问题?

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

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

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

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

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

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

客服 返回
顶部