在 PHP 'switch' 语句中使用比较运算符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24812851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using comparison operators in a PHP 'switch' statement
提问by Jessie Stalk
I have four conditions that I need to go through and I thought it would be best to use the switch
statement in PHP. However, I need to check whether an integer is, let's say, less than or equal, or greater than and equal.
我有四个条件需要通过,我认为最好switch
在 PHP 中使用该语句。但是,我需要检查一个整数是否小于等于,或者大于等于。
switch ($count) {
case 20:
$priority = 'low';
break;
case 40:
$priority = 'medium';
break;
case 60:
$priority = 'high';
break;
case 80:
$priority = 'severe';
break;
}
With an if()
statement it would look like the following:
随着if()
语句看起来会像下面这样:
if ($count <= 20) {
$priority = 'low';
}
if ($count <= 40) {
$priority = 'medium';
}
Is that possible in switch-case
?
这可能switch-case
吗?
回答by Konr Ness
A more general case for solving this problem is:
解决此问题的更一般情况是:
switch (true) {
case $count <= 20:
$priority = 'low';
break;
case $count <= 40:
$priority = 'medium';
break;
case $count <= 60:
$priority = 'high';
break;
default:
$priority = 'severe';
break;
}
回答by bytephunk
There is a way that works in php 7 using ternary assignment operators. The operator was introduced earlier on (5.4?) but I never tested the code on other versions. I wrote the whole switch code there, however for brevity here is just the specific clause. Let's say we want the condition to match for all numbers greater than or equal to five :
有一种方法可以在 php 7 中使用三元赋值运算符。运算符是在 (5.4?) 上较早引入的,但我从未在其他版本上测试过该代码。我在那里写了整个 switch 代码,但是为了简洁起见,这里只是特定的条款。假设我们希望条件匹配所有大于或等于 5 的数字:
switch($value){
case ($value >= 5?$value:!$value)://do something here
break;
}
We either allow the $value to pass unchanged or we negate the value according to the condition. A $value will always match itself or fail the test against its negation.
我们要么允许 $value 不变地传递,要么根据条件否定该值。$value 将始终与自身匹配或无法通过其否定的测试。
回答by Havenard
Switches can't do that, but in this particular case you can do something like this:
开关不能这样做,但在这种特殊情况下,您可以执行以下操作:
switch ((int)(($count - 1) / 20)) {
case 0:
$priority = 'low';
break;
case 1:
$priority = 'medium';
break;
case 2:
$priority = 'high';
break;
case 3:
$priority = 'severe';
break;
}
So in (int)(($count - 1) / 20)
all values from 0 to 20 will eval to 0, 21 to 40 will eval to 1 and so on, allowing you to use the switch statement for this purpose.
因此,在(int)(($count - 1) / 20)
所有值中,从 0 到 20 将 eval 为 0,21 到 40 将 eval 为 1,依此类推,允许您为此目的使用 switch 语句。
And since we are concatenating values, we can even simplify to an array:
由于我们正在连接值,我们甚至可以简化为一个数组:
$priorities = ['low', 'medium', 'high', 'severe'];
$priority = $priorities[(int)(($count - 1) / 20)];
回答by milkncookie
What about using ternary operators?
使用三元运算符怎么样?
$priority =
// "switch" comparison for $count
$count <= 20 ? 'low' :
($count <= 40 ? 'medium' :
($count <= 60 ? 'high' :
// default above 60
'severe'));
I know the common complaint that ternary operators can be hard to understand, but this is just too easy to do with a simple ?:
.
我知道常见的抱怨是三元运算符可能难以理解,但是使用简单的?:
.
It operates like the Excel "If" formula
它的操作类似于 Excel 的“If”公式
=IF( logical_test, value_if_true, value_if_false )
$variable = logical_test ? value_if_true : value_if_false
And you can nest the if statements (place a second ?:
in the 'value_if_false' section of the first one), which is certainly where it can become confusing to read, but less so when you write it out line by line, as above.
并且您可以嵌套 if 语句(?:
在第一个语句的“value_if_false”部分中放置第二个语句),这肯定会导致阅读混乱,但如上所述,当您将其逐行写出时,情况就不那么明显了。
My code above is basically equivalent to the if()
statement written by the OP.
我上面的代码基本上相当于if()
OP写的语句。
回答by Marc B
No. switch()
statements are for doing multiple equality tests. They're basically just a slightly easier to read (but also more hazardous) version of
编号switch()
语句用于进行多个相等性测试。它们基本上只是一个更容易阅读(但也更危险)的版本
if (x == 'a') { ... }
else if (x == 'b') { ... }
else if (x == 'c') { ... }
code. There is no way to change a switch()
away from ==
to <
or any other comparison operator. It's strictly for equality testing.
代码。无法更改switch()
远离 ==
到<
或任何其他比较运算符。它严格用于平等测试。
回答by tfont
I can also confirm @bytepunk answer here is functional.
我也可以确认@bytepunk 在这里的回答是有效的。
Also, expending the concept with PHP 7
另外,用 PHP 7 扩展这个概念
switch ($interval->days)
{
case 0:
return '1 day';
// break;
case (($interval->days >= 1 && $interval->days <= 7) ?? $interval->days):
return '1 week';
// break;
case (($interval->days >= 8 && $interval->days <= 31) ?? $interval->days):
return '1 month';
// break;
case (($interval->days >= 31 && $interval->days <= 93) ?? $interval->days):
return '2-3 months';
// break;
default:
return '3+ months';
}
I will admit that this isn't the cleanest of code, so perhaps wrapping each case with a static-like pure function would neat things up a bit, and not forgetting to name each function (or create one generic function with parameters) to match the case. This will make it more readable.
我承认这不是最干净的代码,所以也许用一个类似静态的纯函数包装每个案例会让事情变得更整洁一点,并且不要忘记命名每个函数(或创建一个带参数的通用函数)以匹配案子。这将使其更具可读性。