嵌套的php三元麻烦:三元输出!= if - else

Pat*_*ick 5 php

我非常有能力使用PHP三元运算符.然而,我试图弄清楚为什么下面的代码与if-else等效结构不匹配时遇到了障碍.测试在不同的数字上运行三次.每个结构的输出都在代码下面.

三元:

$decimal_places = ($max <= 1) ? 2 : ($max > 3) ? 0 : 1;
Run Code Online (Sandbox Code Playgroud)

三元输出:

最大值:-100000十进制:0

最大值:0.48十进制:0

最大值:0.15十进制:0

如果别的

if($max <= 1)
 $decimal_places = 2;
elseif($max > 3)
 $decimal_places = 0;
else
 $decimal_places = 1;
Run Code Online (Sandbox Code Playgroud)

If-Else输出:

最大值:-100000十进制:2

最大值:0.48十进制:2

最大值:0.15十进制:2

任何人都可以告诉我为什么这两个控制结构不输出相同的数据?

Bol*_*ock 18

您的右侧三元表达式需要包含在括号中,因此它将作为单个表达式自行计算:

$decimal_places = ($max <= 1) ? 2 : (($max > 3) ? 0 : 1);

// Another way of looking at it
$decimal_places = ($max <= 1)
                ? 2
                : (($max > 3) ? 0 : 1);
Run Code Online (Sandbox Code Playgroud)

否则,您的三元表达式从左到右进行评估,结果是:

$decimal_places = (($max <= 1) ? 2 : ($max > 3)) ? 0 : 1;

// Another way of looking at it
$decimal_places = (($max <= 1) ? 2 : ($max > 3))
                ? 0
                : 1;
Run Code Online (Sandbox Code Playgroud)

哪个,翻译成if-else,变为:

if ($max <= 1)
    $cond = 2;
else
    $cond = ($max > 3);

if ($cond)
    $decimal_places = 0;
else
    $decimal_places = 1;
Run Code Online (Sandbox Code Playgroud)

因此$decimal_places最终成为0用于的所有值$max除外2,在这种情况下,它的计算结果为1.