unusual ternary operation

后端 未结 7 746
别那么骄傲
别那么骄傲 2020-12-18 21:56

I was asked to perform this operation of ternary operator use:

$test=\'one\';

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


        
7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-18 22:36

    I think that it is evaluated like this:

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

    ($test == 'one' ? 'one' : $test == 'two') is non-zero/null, so 'two' is logical output

    if you want it to work correctly, write:

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

提交回复
热议问题