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

如何在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 ?

图片转代码服务由CSDN问答提供 功能建议

我使用了三元运算符,但我似乎无法将多个三元运算符堆叠在一起。

我知道堆叠多个三元运算符会使代码的可读性降低,但在某些情况下我不喜欢这样做。

这是我到目前为止所尝试的:

  $ foo = 1; 
 $ bar =($ foo == 1)?  “1”:( $ foo == 2)?  “2”:“其他”; 
echo $ bar;  //显示2而不是1 
   
 
 

正确的语法是什么?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

8条回答 默认 最新

  • dongpao5261 2011-06-01 14:45
    已采纳

    Those parenthesis are what I think is getting you.

    Try

    $foo = 1;
    $bar = ($foo == 1) ? "1" : (($foo == 2)  ? "2" : "other");
    echo $bar;
    
    评论
    解决 无用
    打赏 举报
查看更多回答(7条)

相关推荐 更多相似问题