1. Switch statement
The switch statement is used to perform different actions based on multiple different conditions.
If you want to selectively execute one of several blocks of code, use a switch statement.
Syntax:
switch (n)
{
case label1:
If n=label1, the code here will be executed ;
break;
case label2:
If n=label2, the code here will be executed;
break;
default :
If n is neither equal to label1 nor equal to label2, the code here will be executed;
}
Note:
After switch, put the variables that need to be judged, and after case, put the result. What is the variable value after switch? The case value is written in the same code segment as the switch variable.
The above default is also optional and is used to execute the code when no item meets the condition.
The above break is optional, break is used to end various loops unconditionally
Do not write a semicolon after case, followed by a colon:
Do not write a judgment interval after the case, such as ($foo > 20 or $foo == 30)
The variable in switch is preferably an integer or a string, because it is a Boolean judgment More suitable for if...else..
If we use a flow chart to represent it, the result will be as shown below:
Example 1: We still use the rand() function from the previous section to make an example similar to tossing a coin to choose what to do on the weekend
The source code is as follows
<?php $num = rand(1,4); switch($num){ case 1: echo "周末宅在家吧"; break; case 2: echo "周末去爬大蜀山吧"; break; case 3: echo "周末去看电影吧"; break; case 4: echo "周末爱干啥干啥去"; break; } ?>
Please output the result yourself Try it
Note: Try to remove the break from top to bottom and see if there is any change in the output result
Example 2: Use the date() function to make a simple Judge the day of the week
Note: The Date() function formats the timestamp into a more readable date and time.
Please refer to the PHP manual for details. Here we only use date ("D") to obtain the current day of the week in the system.
The source code is as follows:
<?php //得到今天是星期几的英文简称 $day = date('D'); switch($day){ //拿公司举例,我们来创造一个上三休四的制度;让星期一、二、三是工作日 case 'Mon': case 'Tue': case 'Wed': echo '今天是工作日'; break; //星期四、五、六是休息日 case 'Thu': case 'Fri': case 'Sat': echo '今天是休息日'; break; //当都不满足是,必然是星期天,活动日 default: echo '今天是周末,活动日'; } ?>
Note: You can try it yourself and see what the default does