嵌套的php三元麻烦:三元输出!= if-else [英] nested php ternary trouble: ternary output != if - else
问题描述
我相当有能力使用PHP三元运算符.但是,在尝试弄清楚为什么下面的代码与if-else等效结构不匹配时,我遇到了障碍.该测试在不同的编号上运行了3次.每个结构的输出都在代码下方.
I am fairly capable at using the PHP ternary operator. However I have hit a roadblock at trying to figure out why the code below does not match the if-else equivalent structure. The test was run three times on different numbers. The output for each structure is below the code.
三元组:
$decimal_places = ($max <= 1) ? 2 : ($max > 3) ? 0 : 1;
三元输出:
最大值:-100000十进制:0
max: -100000 decimal: 0
最大值:0.48十进制:0
max: 0.48 decimal: 0
最大值:0.15十进制:0
max: 0.15 decimal: 0
If-Else
if($max <= 1)
$decimal_places = 2;
elseif($max > 3)
$decimal_places = 0;
else
$decimal_places = 1;
If-Else输出:
If-Else Output:
最大值:-100000十进制:2
max: -100000 decimal: 2
最大值:0.48十进制:2
max: 0.48 decimal: 2
最大值:0.15十进制:2
max: 0.15 decimal: 2
谁能告诉我为什么这两个控制结构不能输出相同的数据?
Can anyone please tell me why the these two control stuctures do not output the same data?
推荐答案
您的右侧三元表达式需要用括号括起来,这样它就可以作为一个单独的表达式求值:
Your right-hand-side ternary expression needs to be wrapped in parentheses so it'll be evaluated by itself as a single expression:
$decimal_places = ($max <= 1) ? 2 : (($max > 3) ? 0 : 1);
// Another way of looking at it
$decimal_places = ($max <= 1)
? 2
: (($max > 3) ? 0 : 1);
否则,您的三元表达式从左到右求值,结果是:
Otherwise your ternary expression is evaluated from left to right, resulting in:
$decimal_places = (($max <= 1) ? 2 : ($max > 3)) ? 0 : 1;
// Another way of looking at it
$decimal_places = (($max <= 1) ? 2 : ($max > 3))
? 0
: 1;
翻译成if-else的文字变成这样:
Which, translated to if-else, becomes this:
if ($max <= 1)
$cond = 2;
else
$cond = ($max > 3);
if ($cond)
$decimal_places = 0;
else
$decimal_places = 1;
因此,对于$max
以外的所有$max
值,$decimal_places
都以0
结尾,在这种情况下,其值将为1
.
Therefore $decimal_places
ends up as 0
for all values of $max
except 2
, in which case it evaluates to 1
.
这篇关于嵌套的php三元麻烦:三元输出!= if-else的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!