PHP-带条件开关的开关案例语句
我可以将条件语句放在 switch 语句中吗?ex - switch ($totaltime<=13) 除了php,其他语言兼容性如何?
Can i put conditional statement within switch statement. ex - switch ($totaltime<=13) Other than php how about other languages compatibility with it?
$totaltime=15;
switch ($totaltime<=13) {
case ($totaltime <= 1):
echo "That was fast!";
break;
case ($totaltime <= 5):
echo "Not fast!";
break;
case ($totaltime >= 10 && $totaltime<=15):
echo "That's slooooow";
break;
}
编辑
$totaltime=12;
switch (false) {
case ($totaltime <= 1):
echo "That was fast!";
break;
case ($totaltime <= 5):
echo "Not fast!";
break;
case ($totaltime >= 10 && $totaltime<=13):
echo "That's slooooow";
break;
default: // do nothing break;
}
绅士在这种情况下,为什么总是将输出显示为太快了!"?
Gentleman in this case why alwyas show output as "That was fast!"?
推荐答案
Switch只检查第一个条件是否等于第二个,这样:
Switch only checks if the first condition is equal to the second, this way:
switch (CONDITION) {
case CONDITION2:
echo "CONDITION is equal to CONDITION2";
break;
}
所以你必须这样做:
switch (true) {
case $totaltime <= 1: #This checks if true (first condition) is equal to $totaltime <= 1 (second condition), so if $totaltime is <= 1 (true), is the same as checking true == true.
echo "That was fast!";
break;
case $totaltime <= 5:
echo "Not fast!";
break;
case $totaltime >= 10 && $totaltime<=13:
echo "That's slooooow";
break;
}
我将使用 if-elseif
语句而不是这个.乍一看更容易理解:
Instead of this i'll go for if-elseif
statements. Is easier to understand at first sight:
if ($totaltime <= 1) {
echo "That was fast!";
} elseif($totaltime <= 5) {
echo "Not fast!";
} elseif($totaltime >= 10 && $totaltime<=13) {
echo "That's slooooow";
}
相关文章