【问题标题】:PHP multiple ternary operator not working as expectedPHP多三元运算符未按预期工作
【发布时间】:2012-12-22 06:33:06
【问题描述】:

为什么要打印2

echo true ? 1 : true ? 2 : 3;

据我了解,应该打印1

为什么没有按预期工作?

【问题讨论】:

  • 嵌套三元运算符从来都不是很好的理由......并且手册明确警告您这一点
  • php.net/manual/en/language.operators.comparison.php - Note: It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious - 三元表达式是左关联的。
  • 如果你必须嵌套你的三元运算符,那么在它们周围使用括号。事实上,我还是建议在三元组周围使用方括号;即使您没有嵌套它们,它也会使它们更具可读性。

标签: php ternary-operator


【解决方案1】:

因为你写的是一样的:

echo (true ? 1 : true) ? 2 : 3;

如您所知,1 被评估为true

你所期望的是:

echo (true) ? 1 : (true ? 2 : 3);

所以总是使用大括号来避免这种混淆。

如前所述,三元表达式在 PHP 中保留关联。这意味着首先将执行 left 的第一个,然后是第二个,依此类推。

【讨论】:

    【解决方案2】:

    如有疑问,请使用括号。

    与其他语言相比,PHP 中的三元运算符是左结合的,不能按预期工作。

    【讨论】:

      【解决方案3】:

      用括号分隔第二个三元子句。

      echo true ? 1 : (true ? 2 : 3);
      

      【讨论】:

        【解决方案4】:

        来自docs

        Example #3 Non-obvious Ternary Behaviour
        <?php
        // on first glance, the following appears to output 'true'
        echo (true?'true':false?'t':'f');
        
        // however, the actual output of the above is 't'
        // this is because ternary expressions are evaluated from left to right
        
        // the following is a more obvious version of the same code as above
        echo ((true ? 'true' : false) ? 't' : 'f');
        
        // here, you can see that the first expression is evaluated to 'true', which
        // in turn evaluates to (bool)true, thus returning the true branch of the
        // second ternary expression.
        ?>
        

        【讨论】:

          【解决方案5】:

          在你的情况下,你应该考虑执行语句的优先级。

          使用以下代码:

          echo true ? 1 : (true ? 2 : 3);
          

          例如,

          $a = 2;
          $b = 1;
          $c = 0;
          
          $result1 = $a ** $b * $c;
          // is not equal
          $result2 = $a ** ($b * $c);
          

          你在数学表达式中使用过括号吗? - 然后,根据执行优先级,结果是不一样的。在您的情况下,三元运算符的编写没有优先级。让解释器了解使用括号执行操作的顺序。

          【讨论】:

            【解决方案6】:

            晚了,但是从现在开始小心的一个很好的例子:

            $x = 99;
            print ($x === 1) ? 1
                : ($x === 2) ? 2
                : ($x === 3) ? 3
                : ($x === 4) ? 4
                : ($x === 5) ? 5
                : ($x === 99) ? 'found'
                : ($x === 6) ? 6
                : 'not found';
            // prints out: 6
            

            PHP 7.3.1(Windows 命令行)的结果。我不明白他们为什么要更改它,因为如果我尝试更改它,代码变得非常不可读。

            【讨论】:

              猜你喜欢
              • 2020-01-09
              • 2019-12-10
              • 2018-02-19
              • 1970-01-01
              • 2018-11-14
              • 1970-01-01
              • 2016-01-13
              • 1970-01-01
              相关资源
              最近更新 更多