[英]PHP- Switch case statement with conditional switch
我可以将条件语句放在 switch 语句中吗? ex - switch ($totaltime<=13) 除了php,其他语言的兼容性如何?
$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;
}
绅士在这种情况下为什么总是将输出显示为“太快了!”?
Switch 只检查第一个条件是否等于第二个条件,这样:
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
语句。 乍一看更容易理解:
if ($totaltime <= 1) {
echo "That was fast!";
} elseif($totaltime <= 5) {
echo "Not fast!";
} elseif($totaltime >= 10 && $totaltime<=13) {
echo "That's slooooow";
}
是的,你可以(除了开关内的比较)
$totaltime=12;
switch (true) {
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;
}
是的,你可以,从 PHP 的 switch 文档中:
switch 语句类似于同一表达式上的一系列 IF 语句。 在许多情况下,您可能希望将同一个变量(或表达式)与许多不同的值进行比较
当 case 具有常量值时,就像在说 case value == switch value,但是您可以为 case 使用更复杂的表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.