dsaf32131 2011-06-01 06:43
浏览 91
已采纳

如何在PHP中连接多个三元运算符?

I use ternary operators alot but I can't seem to stack multiple ternary operator inside each other.

I am aware that stacking multiple ternary operator would make the code less readable but in some case I would like to do it.

This is what I've tried so far :

$foo = 1;
$bar = ( $foo == 1 ) ? "1" : ( $foo == 2 ) ? "2" : "other";
echo $bar; // display 2 instead of 1

What is the correct syntax ?

  • 写回答

8条回答 默认 最新

  • dongpao5261 2011-06-01 06:45
    关注

    Those parenthesis are what I think is getting you.

    Try

    $foo = 1;
    $bar = ($foo == 1) ? "1" : (($foo == 2)  ? "2" : "other");
    echo $bar;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部