本文介绍了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.
这篇关于PHP CASE 语句不适用于零值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!