doumen6605 2014-10-20 18:53
浏览 23
已采纳

PHP-使用条件开关切换case语句

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;
}

Edit

$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!"?

  • 写回答

3条回答 默认 最新

  • dqzow3859 2014-10-20 19:04
    关注

    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;
    }
    

    So you have to do it this way:

    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;
    }
    

    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";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?
  • ¥15 求MCSCANX 帮助
  • ¥15 机器学习训练相关模型
  • ¥15 Todesk 远程写代码 anaconda jupyter python3
  • ¥15 我的R语言提示去除连锁不平衡时clump_data报错,图片以下所示,卡了好几天了,苦恼不知道如何解决,有人帮我看看怎么解决吗?
  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?