开关不适用于数字比较用例 [英] Switch doesn't work with numeric comparison cases
问题描述
这是我的代码.
$value = 0;
switch($value) {
case ( $value <= 25 ):
$CompScore = 'low';
break;
case ($value > 25 && $value <= 50 ):
$CompScore = 'fair';
break;
case ($value > 50 && $value <= 75 ):
$CompScore = 'good';
break;
case ($value >75 ):
$CompScore = 'excellent';
break;
default:
$CompScore = 'low';
break;
}
echo $CompScore;
当值为0
时,$compScore
为fair
.为什么不显示low
?我不明白为什么.
When the value is 0
, $compScore
is fair
. Why it is not showing low
? I don't understand why.
推荐答案
您传递到switch语句中的值基本上就是switch语句寻找要评估的匹配项的内容,从案例列表的顶部到底部一直到它找到一个等于的(松散比较),例如true == true
.
The value you pass into a switch statement is basically what the switch statement looks for an evaluated match for, going from top to bottom down the list of cases until it finds one it is equal to (loose comparison), e.g. true == true
.
在您的示例中,您的比较被评估为布尔值(对或错)-您的变量$value
为设置为零,即与false
相等(等于),但对false
而言,相同(严格比较).例如:
In your example, your comparisons are evaluated as booleans (true or false) - your variable $value
is set to zero, which is equal to false
, but not identical (strict comparison) to false
. For example:
(0 == false) // true
(0 === false) // false
(1 == false) // false
(1 === false) // false
(1 == true) // true
(1 === true) // false
(true === true) // true
因此,通过使用布尔值true
作为切换值,您可以执行以下操作:在语句内包含数字比较,其中每个比较的结果将为true
或false
,以匹配/不匹配原始的true
值(布尔-布尔比较).
So by using a boolean true
as your switch value, you can do this to have numeric comparison inside the statement, where each comparison will evaluate to either true
or false
to match/not match the original true
value (boolean - boolean comparison).
switch(true) {
case ($value <= 25): // true
$CompScore = 'low';
break;
case ($value > 25 && $value <= 50 ): // false
$CompScore = 'fair';
break;
case ($value > 50 && $value <= 75 ): // false
$CompScore = 'good';
break;
case ($value >75 ): // false
$CompScore = 'excellent';
break;
default: // if you removed the first case
$CompScore = 'low'; // this default case would be used
break;
}
这篇关于开关不适用于数字比较用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!