14

我被要求执行三元运算符使用的这个操作:

$test='one';

echo $test == 'one' ? 'one' :  $test == 'two' ? 'two' : 'three';

打印两个(使用 php 检查)。

我仍然不确定这样做的逻辑。拜托,谁能告诉我这个的逻辑。

4

7 回答 7

15

那么,? 和 : 具有相同的优先级,因此 PHP 将依次从左到右解析每个位:

echo ($test == 'one' ? 'one' :  $test == 'two') ? 'two' : 'three';

First$test == 'one'返回 true,因此第一个括号的值为 'one'。现在第二个三元的评估如下:

'one' /*returned by first ternary*/ ? 'two' : 'three'

'one' 为真(非空字符串),所以 'two' 是最终结果。

于 2010-04-17T14:39:18.147 回答
7

基本上解释器从左到右评估这个表达式,所以:

echo $test == 'one' ? 'one' :  $test == 'two' ? 'two' : 'three';

被解释为

echo ($test == 'one' ? 'one' :  $test == 'two') ? 'two' : 'three';

并且括号中的表达式计算为真,因为“一”和“二”都不是 null/o/其他形式的假。所以如果它看起来像:

echo $test == 'one' ? FALSE :  $test == 'two' ? 'two' : 'three';

它会打印三个。为了使其正常工作,您应该忘记组合三元运算符,并使用常规 ifs/switch 来处理更复杂的逻辑,或者至少使用方括号,以便解释器理解您的逻辑,而不是以标准 LTR 方式执行检查:

echo $test == 'one' ? 'one' :  ($test == 'two' ? 'two' : ($test == 'three' ? 'three' : 'four'));

//etc... It's not the most understandable code... 

//You better use:
if($test == 'one')
    echo 'one';
else { //or elseif()
...
}

//Or:
switch($test) {
    case 'one':
        echo 'one';
        break;
    case 'two':
        echo 'two';
        break;
//and so on...
}
于 2010-04-17T14:41:59.193 回答
5

使用括号时它可以正常工作:

<?
 $test='one';
 echo $test == 'one' ? 'one' :  ($test == 'two' ? 'two' : 'three');

我不是 100% 理解它,但没有括号,对于解释器,语句必须如下所示:

echo ($test == 'one' ? 'one' :  $test == 'two') ? 'two' : 'three';

第一个条件的结果似乎是作为整个三元运算的结果返回的。

于 2010-04-17T14:35:35.030 回答
1

PHP的文档说:

注意:建议您避免“堆叠”三元表达式。在单个语句中使用多个三元运算符时 PHP 的行为并不明显:

Example #3 不明显的三元行为

<?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.
?>

如果你在错误语句周围加上括号,它会打印one

echo $test == 'one' ? 'one' :  ($test == 'two' ? 'two' : 'three');
于 2010-04-17T14:34:20.300 回答
1

我认为它是这样评估的:

echo ($test == 'one' ? 'one' :  $test == 'two') ? 'two' : 'three';

($test == 'one' ? 'one' : $test == 'two') 非零/空,所以 'two' 是逻辑输出

如果您希望它正常工作,请编写:

echo $test == 'one' ? 'one' :  ($test == 'two' ? 'two' : 'three');
于 2010-04-17T14:36:40.873 回答
1

三元运算符按出现顺序执行,因此您确实拥有:

echo ($test == 'one' ? 'one' :  $test == 'two') ? 'two' : 'three';
于 2010-04-17T14:57:09.667 回答
0

嵌套的三元运算太恶心了!上面的解释说明了原因。

基本上是这样的逻辑:

is $test == 'one'

  if TRUE then echo 'one'

  else is $test == 'two'

      if TRUE then echo 'two'

      else echo three
于 2010-04-17T14:35:17.233 回答