什么可能是echo的输出('True'?(true?'t':'f'):'False');并解释原因?

时间:2012-02-07 07:07:46

标签: php operators ternary-operator

  

可能重复:
  What is the PHP ? : operator called and what does it do?

我接受了一个非常基本的PHP问题的采访,就像:

echo ('True' ? (true ? 't' : 'f') : 'False');

有人可以解释它会产生的输出细节吗?

由于

7 个答案:

答案 0 :(得分:4)

看看这个版本应该说清楚:

if('True'){ // evaluates true
    if(true){ // evaluates tre
        echo 't'; // is echo'd
    }else{
        echo 'f';
    }
}else {
    echo 'False';
}

答案 1 :(得分:4)

这将回显 t

因为它首先会检查第一个给出真实的条件。 然后在下一个条件下,它再次给出真实并执行 t 的第一个条件。

在if和else条件下,它将写成如下:

if('True') { //condition true and go to in this block
   if(true){ //condition true and go to in this block
      echo 't'; // echo t
   } else {
      echo 'f';
   }
} else {
   echo 'False';
}

答案 2 :(得分:4)

除了字符串"0"之外,非空字符串被视为真值。 PHP评估

'True' ? (true ? 't' : 'f') : 'False'

从左到右依次如下:

  • 表达式'True'被评估为布尔值true
  • 接下来,评估?之后的表达式
    • 表达式true是...... true!
    • 返回?后面的表达式,即 t

令人惊讶的是,如果表达式为:

,您仍然会 t
echo 'False' ? (true ? 't' : 'f') : 'False'

答案 3 :(得分:3)

由于'True'被评估为true

if('True'){
    if(true){
        echo 't';
    }else{
        echo 'f';
    }
}else{
    echo 'False';
}

答案 4 :(得分:3)

内括号将首先执行true?'t':'f'它将返回't',这是一个字符串

现在外部条件将检查echo ('True' ? 't' : 'False')。这里'True'是一个“非空字符串”(隐式转换为TRUE),因此它计算为true,并返回't'。

最终代码为echo ('t'),只会回显t

答案 5 :(得分:3)

echo ( // will echo the output
  'True'? // first ternary operation 'True' is considered true
    (true? 't':'f') // will go here for the second ternary operation
                    // true is also evaluated as true so it will echo 't'

  : 'False'); // never goes here

答案 6 :(得分:3)

此:

'True'?(true?'t':'f'):'False'

可以写成

// Will always be true if String is not an Empty string. 
if('True'){ 
   // if (true) will always enter
   if(true){ 
      // t will be the output
      echo 't'; 
   }else{
      echo 'f';
}
else {
    echo 'False';
}
相关问题