本文介绍了int = 0上的php switch语句错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 php switch case 中遇到了问题.
I am having a problem in php switch case.
当我设置 $number=0 时,它应该运行第一个 case 但这里代码返回 10-20K,这是第二种情况.
When i set $number=0 it should run very first case but here this code returns 10-20K that is in second case.
我检查了比较运算符,在其他情况下测试它们返回正确的值,但这里第一种情况不会在 $number=0
I checked comparison operators, tested them in if else case they return correct values but here first case do not run on $number=0
为什么会这样?php 认为 0 为 false 或代码有问题?
Why is this happening ? php consider 0 as false or something wrong in code ?
键盘粘贴链接http://codepad.org/2glDh39K
这里也是代码
<?php
$number = 0;
switch ($number) {
case ($number <= 10000):
echo "0-10K";
break;
case ($number > 10000 && $number <= 20000):
echo "10-20K";
break;
case ($number > 20000 && $number <= 30000):
echo "20-30K";
break;
case ($number > 30000 && $number <= 40000):
echo "30-40K";
break;
case ($number > 40000 && $number <= 50000):
echo "40-50K";
break;
case ($number > 50000 && $number <= 60000):
echo "50-60K";
break;
case ($number > 60000 && $number <= 70000):
echo "60-70K";
break;
case ($number > 70000 && $number <= 80000):
echo "70-80K";
break;
case ($number > 80000 && $number <= 90000):
echo "80-90K";
break;
case ($number > 90000):
echo "90K+";
break;
default: //default
echo "N/A";
break;
}
?>
推荐答案
switch ($number) {
case ($number <= 10000): // check $number == ($number <= 10000)
echo "0-10K";
break;
// you hit the below because `0 == false` is true in php
case ($number > 10000 && $number <= 20000): // check $number == ($number > 10000 && $number <= 20000)
echo "10-20K";
break;
// ...
但你可以用更少的代码做到这一点:
But you could do it with less code:
function showRange($number) {
if ($number > 90000) {
echo "90K+";
return;
}
echo sprintf("%s-%sK", (int) ($number / 10000) * 10, ((int) ($number / 10000) +1) * 10 );
}
这篇关于int = 0上的php switch语句错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!