PHP中如何连接多个三元运算符?
我经常使用三元运算符,但我似乎无法将多个三元运算符堆叠在一起。
我知道堆叠多个三元运算符会使代码可读性较差,但在某些情况下我会 喜欢这样做。
这是我到目前为止所尝试过的:
$foo = 1;
$bar = ( $foo == 1 ) ? "1" : ( $foo == 2 ) ? "2" : "other";
echo $bar; // display 2 instead of 1
正确的语法是什么?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
我认为这些括号是让你明白的。
尝试
Those parenthesis are what I think is getting you.
Try
问题在于,与所有其他语言不同,PHP 使条件运算符左结合。这会破坏你的代码——这在其他语言中是没问题的。
您需要使用括号:(
请注意,我已从代码中删除了其他括号;但这些是正确的,只是多余的。)
The problem is that PHP, unlike all other languages, makes the conditional operator left associative. This breaks your code – which would be fine in other languages.
You need to use parentheses:
(Notice that I’ve removed the other parentheses from your code; but these were correct, just redundant.)
您需要在右手操作数周围添加一些括号:
PHP 的解释器已损坏,并将您的行视为:
因为
左手表达式的计算结果为“true”,剩余三元运算符的第一个操作数 (“2 ") 被返回。
You need some parentheses around the right hand operand:
PHP's interpreter is broken, and treats your line:
as
and since that left hand expression evaluates as "true" the first operand of the remaining ternary operator ("2") is returned instead.
在每个内部三元运算符两边加上括号,这样可以保证运算符的优先级:
Put parenthesis around each inner ternary operator, this way operator priority is assured:
您可以这样正确地编写:(
即:只需将“内部”三元运算符嵌入括号中。)
但是,我真的很想不这样做,因为它的可读性与特定的难以辨认的东西被严重弄脏了——从来没有任何借口来混淆代码,这就是它的边界。
You could write this correctly thus:
(i.e.: Simply embed the 'inner' ternary operator in parenthesis.)
However, I'd be really tempted not to do this, as it's about as readable as a particularly illegible thing that's been badly smudged - there's never any excuse for obfuscating code, and this borders on it.
只要把括号叠起来,你就得到了它:
顺便说一句,如果你有很多子句,你应该考虑使用
switch
:如果 switch 很长,你可以将它包裹起来一个函数。
Just stack up the parenthesis, and you've got it:
As an aside, if you've got many clauses, you should consider using a
switch
:If the switch gets long, you can wrap it in a function.
只需使用额外的 ( ) 即可工作
Just use extra ( ) and it will work
添加括号:
Add the parenthesis: