PHP CASE 语句不适用于零值
我不明白这里发生了什么.从逻辑上讲,这对我来说没有任何意义.
I don't understand what's happening here. Logically, it doesn't make any sense to me.
<?php
$level = 0;
switch ($level) {
case $level > 80: $answer = 'high'; break;
case $level > 60: $answer = 'moderate-to-high'; break;
case $level > 40: $answer = 'moderate'; break;
case $level > 20: $answer = 'low-to-moderate'; break;
default: $answer = 'low'; break;
}
echo $answer;
?>
当 $level == 0 时,返回high".这对我来说没有任何意义.有人可以解释这里发生了什么吗?
When $level == 0, it returns "high". This doesn't make any sense to me. Can someone explain what's happening here?
推荐答案
将 switch ($level)
改为 switch (true)
即可.
switch
语句执行相等性测试关于案例中的价值观.PHP 正在评估您的 >
比较,所以 case $level >80
变为 case false
.false
被认为等于 0
,所以第一种情况匹配.
switch
statements perform equality tests on the values in the cases. PHP is evaluating your >
comparisons, so case $level > 80
becomes case false
. false
is considered to be equal to 0
, so the first case matches.
相关文章