Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP5.3.3谜题,打印什么以及为什么_Php_Puzzle_Ternary Operator - Fatal编程技术网

PHP5.3.3谜题,打印什么以及为什么

PHP5.3.3谜题,打印什么以及为什么,php,puzzle,ternary-operator,Php,Puzzle,Ternary Operator,为什么它不打印应该打印的内容 <?php $place = 1; echo $place === 1 ? 'a' : $place === 2 ? 'b' : 'c'; ?> 这就是原因。。引述: 条件运算符从左到右求值,因此应该编写 echo ($place === 1 ? 'a' : $place === 2) ? 'b' : 'c'; echo (true ? 'a' : $place === 2) ? 'b' : 'c'; echo 'a'

为什么它不打印应该打印的内容

<?php 
$place = 1; 
echo $place === 1 ? 'a' : $place === 2 ? 'b' : 'c'; 
?>

这就是原因。

。引述:


条件运算符从左到右求值,因此应该编写

echo ($place === 1 ? 'a' : $place === 2)  ? 'b' : 'c';
echo (true         ? 'a' : $place === 2)  ? 'b' : 'c';
echo 'a'                                  ? 'b' : 'c';
echo true                                 ? 'b' : 'c'; // outputs b

澄清。这种行为是。

你认为它应该打印什么,为什么,打印什么

另外,从PHP三元表达式手册:

注:

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



我没有看到任何打印内容:?从手册中“建议您避免“堆叠”三元表达式。PHP在一条语句中使用多个三元运算符时的行为并不明显:“@Karthik:因为
$place!==1
??如果不是在这种情况下,
$place
实际是
==1
,我对这行感到困惑,我是说他检查的是a是空的??或者别的什么???@mb开发人员PHP是松散类型的,并且做很多类型的杂耍。在PHP中,
'a'==true
(因为
'a'
是一个非空、非零的字符串)谢谢,我刚刚混淆了他的第二个条件,但现在明白了为什么它是true。
<?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.
echo ($place === 1 ? 'a' : $place === 2) ? 'b' : 'c';
// which is
echo 'a' ? 'b' : 'c';
// which is
echo 'b';
echo ($place === 1 ? 'a' : $place === 2)  ? 'b' : 'c';
echo (true         ? 'a' : $place === 2)  ? 'b' : 'c';
echo 'a'                                  ? 'b' : 'c';
echo true                                 ? 'b' : 'c'; // outputs b
<?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.

?>