PHP-带条件开关的开关案例语句

PHP- Switch case statement with conditional switch(PHP-带条件开关的开关案例语句)
本文介绍了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";
}

这篇关于PHP-带条件开关的开关案例语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)