15

为什么要这样打印2

echo true ? 1 : true ? 2 : 3;

据我了解,它应该打印1.

为什么它没有按预期工作?

4

6 回答 6

27

因为您写的内容与以下内容相同:

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

如您所知, 1 被评估为true

你期望的是:

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

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

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

于 2013-01-08T11:59:46.607 回答
3

有疑问时使用括号。

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

于 2013-01-08T12:00:09.707 回答
3

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

echo true ? 1 : (true ? 2 : 3);
于 2013-01-08T12:00:11.797 回答
2

文档

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.
?>
于 2013-01-08T12:00:29.870 回答
0

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

使用以下代码:

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

例如,

$a = 2;
$b = 1;
$c = 0;

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

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

于 2019-12-07T05:12:28.377 回答
0

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

$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-09-14T06:30:12.120 回答