How can I understand nested ?: operators in PHP? [duplicate]

。_饼干妹妹 提交于 2019-12-01 22:54:02

Bracketing is the solution for both understanding and fixing:

This should have the unintended result (horse):

$arg = 'T';  
$vehicle = (
    (
        (
            (
                (
                    ( $arg == 'B' ) ? 'bus' : ( $arg == 'A' )
                ) ? 'airplane' : ( $arg == 'T' )
            ) ? 'train' : ( $arg == 'C' )
        ) ? 'car' : ( $arg == 'H' )
    ) ? 'horse' : 'feet'
);  
echo $vehicle;

This should have the indended result (train):

$arg = 'T';   
$vehicle = (
    ( $arg == 'B' ) ? 'bus' : (
        ( $arg == 'A' ) ? 'airplane' : (
            ( $arg == 'T' ) ? 'train' : (
                ( $arg == 'C' ) ? 'car' : (
                    ( $arg == 'H' ) ? 'horse' : 'feet'
                )
            )
        )
    )
);   
echo $vehicle;

Note:

It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious:

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

http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!