PHP switch...case
在本教程中,你将学习如何使用 switch-case 语句在 PHP 中测试或评估具有不同值的表达式。
PHP if...else
vs switch...case
switch-case 语句是 if-elseif-else 语句的替代语句,它几乎完全相同。switch-case 语句针对一系列值测试变量,直到找到匹配项,然后执行与该匹配项对应的代码块。
switch (n){ case label1: // Code to be executed if n=label1 break; case label2: // Code to be executed if n=label2 break; ... default : // Code to be executed if n is different from all labels }
请考虑以下示例,该示例显示每天的不同消息。
<?php
$today = date("D");
switch($today){
case "Mon":
echo "Today is Monday. Clean your house.";
break;
case "Tue":
echo "Today is Tuesday. Buy some food.";
break;
case "Wed":
echo "Today is Wednesday. Visit a doctor.";
break;
case "Thu":
echo "Today is Thursday. Repair your car.";
break;
case "Fri":
echo "Today is Friday. Party tonight.";
break;
case "Sat":
echo "Today is Saturday. Its movie time.";
break;
case "Sun":
echo "Today is Sunday. Do some rest.";
break;
default:
echo "No information available for that day.";
break;
}
?>
该 switch-case
语句与 if-elseif-else
在一个重要方面与语句不同。 switch
语句逐行执行(即语句逐语),一旦 PHP 找到一个 case
计算结果为 true
的语句,它不仅会执行与该 case 语句对应的代码,还会自动执行所有后续 case
语句直到该 switch
块结束。
为了防止这种情况,在每个 case
块的末尾添加一个 break
语句。该 break
语句告诉 PHP 在 switch-case
执行与第一个为 True
的 case
相关联的代码后跳过后面的语句块。