nik*_*nik 14 php logic ternary-operator logical-operators
我被要求执行三元运算符使用的这个操作:
$test='one';
echo $test == 'one' ? 'one' : $test == 'two' ? 'two' : 'three';
Run Code Online (Sandbox Code Playgroud)
其中打印两个(使用php检查).
我仍然不确定这个的逻辑.拜托,有谁可以告诉我这个的逻辑.
Nic*_*son 15
好吧,?和:具有相同的优先级,因此PHP将从左到右解析依次评估每个位:
echo ($test == 'one' ? 'one' : $test == 'two') ? 'two' : 'three';
Run Code Online (Sandbox Code Playgroud)
首先$test == 'one'返回true,所以第一个parens的值为'one'.现在第二个三元评估如下:
'one' /*returned by first ternary*/ ? 'two' : 'three'
Run Code Online (Sandbox Code Playgroud)
'one'为真(非空字符串),因此'two'是最终结果.
基本上,解释器从左到右评估此表达式,因此:
echo $test == 'one' ? 'one' : $test == 'two' ? 'two' : 'three';Run Code Online (Sandbox Code Playgroud)
被解释为
echo ($test == 'one' ? 'one' : $test == 'two') ? 'two' : 'three';Run Code Online (Sandbox Code Playgroud)
并且paratheses中的表达式评估为true,因为'one'和'two'都不是null/o /其他形式的false.所以,如果它看起来像:
echo $test == 'one' ? FALSE : $test == 'two' ? 'two' : 'three';Run Code Online (Sandbox Code Playgroud)
它将打印三个.为了使它工作正常,您应该忘记组合三元运算符,并使用常规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...
}
Run Code Online (Sandbox Code Playgroud)
使用括号时它可以正常工作:
<?
$test='one';
echo $test == 'one' ? 'one' : ($test == 'two' ? 'two' : 'three');
Run Code Online (Sandbox Code Playgroud)
我不理解它100%但没有括号,对于解释器,语句必须如下所示:
echo ($test == 'one' ? 'one' : $test == 'two') ? 'two' : 'three';
Run Code Online (Sandbox Code Playgroud)
第一个条件的结果似乎是整个三元运算的结果.