The switch statement is used to perform different actions based on multiple different conditions.
We have learned the if...else statement to determine conditions before, but it is inefficient. Is there any other better way? One way we can use is: switch...case syntax. The syntax structure of
switch...case is as follows:
switch (expr)
##{
case expr1:
statement ;break;
case expr2:
statement;
break;
……
default:
statement;
}
The switch statement is similar to a series of if statements with the same expression
Each case will be judged in turn, expr Is it equal to expr1..n? If equal, the corresponding statement will be executed. If there is a break at the end, the switch statement will jump out after the execution is completed.
default is the default operation performed when all cases cannot be satisfied
Notes:1. Do not write a semicolon after case, followed by a colon:
2. Do not write a judgment interval after case. For example ($foo > 20 or $foo == 30)
3. The variables in switch are preferably integers or strings, because Boolean judgment is more suitable for if...else..
4. If you remove the break in each case, then the code blocks in each case will be executed in sequence until5. The switch statement does not need to be written default, but as a good habit, it is recommended to keep the default statement
Instance<?php
header("Content-type:text/html;charset=utf-8"); //设置编码
$dir='north';
switch ($dir) {
case 'west':
echo '西';
break;
case 'east':
echo '东';
break;
case 'north':
echo '北';
break;
case 'sourth':
echo '南';
break;
default:
echo '未知';
break;
}
Let’s write a simple week judgment:
<?php header("Content-type:text/html;charset=utf-8"); //设置编码 //得到今天是星期几的英文简称 $day = date('D'); switch($day){ //拿学校举例,我们让星期一、二、三是校长日 case 'Mon': case 'Tue': case 'Wed': echo '校长日'; break; case 'Thu': echo '星期四'; break; case 'Fri': echo '星期五'; break; default: echo '周末,周末过的比周一到周五还要累<br />'; }Look at what day it is today.
Next Section