在 PHP 中使用三元运算符(? 和 :) 时允许使用多少条语句?
该代码
count = $a > $b ? $b : $a;
与:
if($a > $b){
count = $b;
} else {
count = $a;
}
如果我想这样做,
if($a > $b){
count = $b;
result = $b." is less than ".$a;
} else {
count = $a;
}
我应该如何使用三元运算符 编写这些代码? :
...?
This code,
count = $a > $b ? $b : $a;
same with:
if($a > $b){
count = $b;
} else {
count = $a;
}
If I want to do this,
if($a > $b){
count = $b;
result = $b." is less than ".$a;
} else {
count = $a;
}
How should I write these using a ternary operator ? :
...?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
实际上,您可以将所有内容都放入一行中,但它很难阅读,并且可能无法始终有效。
为了向您展示这是可行的:
但请永远不要在任何实际代码中执行此操作 - 这将使您非常不受那些必须与您/在您之后使用相同代码的人的欢迎。
如果您必须在实际代码中使用三元运算符,请按照其他人的建议进行操作。
You can actually fit this all into 1 line, but it's difficult to read and probably won't work all of the time.
For the sake of showing you this works:
But please never do this in any real code - It will make you very unpopular with anyone who has to work on the same code with you/after you.
If you must use the ternary operator in real code, do it as others have suggested.
你不能用一行来完成它。对不起。
You can't do it in a single line. Sorry.
为什么你要问如何让你的代码更糟糕?
让代码完全不可读有什么意义?
不要尝试在三元运算符中放入许多语句。
不要使用嵌套三元运算符。
您不仅要尽快编写代码,有时还必须阅读它。
不要使用这种丑陋的语法,而是使用常见的条件运算符。
Why you're asking how to make your code worse?
What's the point in making the code totally unreadable?
Do not try to put many statements in the ternary operator.
Do not use nested ternary operators.
You have no only write your code as fast as possible, but sometimes you have to read it.
Instead of using this ugly syntax, use common conditional operator.
你真的不能,这不是三元运算符的重点。您必须执行两个语句,或者写出 if else。
我认为这是有效的 PHP。您可能需要一些括号,并且可能需要在第二行的冒号后面放置一个虚拟常量 - 只需一个 0,以便 PHP 可以做一些事情。我不确定,因为我不会 PHP。
You really can't, that isn't the point of the ternary operator. You would have to do two statements, or write out the if else.
Which is I think valid PHP. You may need some parens, and you might need to put a dummy constant after the colon in the second line - just a 0 so PHP has something to do. I'm not sure because I don't PHP.