Har*_*rry 3 php switch-statement
信息
我目前正在为我的网站制作用户级系统.我的用户表中有一个点列,它会在某些奖项和里程碑等上增加.
问题
我有这个switch语句,它接受用户点并将它们转换为返回的级别.但它是说"0"不在0-100选项中,而是在100-200选项中.
function userLevel($points){
switch ($points) {
case ($points>=0 && $points<100):
return 1; // Level 1
break;
case ($points>=100 && $points <200):
return 2; // Level 2
break;
case ($points>=200 && $points<300):
return 3; // Level 3
break;
case ($points>=300 && $points<400):
return 4; // Level 4
break;
}
}
echo userLevel(0);
Run Code Online (Sandbox Code Playgroud)
我觉得这就是"你一直在为一次坐着编码太多"的问题之一,答案就在我面前,但我看不到它!
由于您的案例使用条件,您可能想要打开TRUE:
function userLevel($points){
switch (true) {
case ($points>=0 && $points<100):
return 1; // Level 1
break;
case ($points>=100 && $points <200):
return 2; // Level 2
break;
case ($points>=200 && $points<300):
return 3; // Level 3
break;
case ($points>=300 && $points<400):
return 4; // Level 4
break;
}
}
Run Code Online (Sandbox Code Playgroud)