Use of branch structure switch statement in PHP flow control
The use of branch structure switch statements
I still remember the story we told at the beginning:
Classmate Wang’s family is very rich, so his schedule is the same as normal Humans are a little different.
There are 6 ways for him to travel, as follows:
1, driver driving
2, civil aviation
3, His own private plane
4, train
5, horse riding
6, cruise ship
his way There are 6 types, and the dice are really good with 6 sides. Therefore, we can use the if...elseif... judgment method, but the efficiency is too low.
Is there any other better way? One way we can use is: switch...case syntax.
The syntax structure of switch...case is as follows:
<?php switch(变量){ //字符串,整型 case 具体值: 执行代码; break; case 具体值2: 执行代码2; break; case 具体值3: 执行代码3; break; default: } ?>
The variable to be judged is placed after switch, and the result is placed after case. What is the value after the switch? The case value is written in the same code as the switch variable.
The above break is optional
The above default is also optional
Do not write a semicolon after case, followed by a colon:
Do not write in case Write the judgment interval later, such as ($foo > 20 or $foo == 30)
The variables in switch are preferably integers or strings, because Boolean judgments are more suitable for if...else..
If we use a flow chart to represent it, the result will be as shown below:
We used the rand function in the last class, so now let’s use rand to implement Wang Sixong’s question selection:
<?php //定义出行工具 $tool=rand(1,6); switch($tool){ case 1: echo '司机开车'; break; case 2: echo '民航'; break; case 3: echo '自己家的专机'; break; case 4: echo '火车动车'; break; case 5: echo '骑马'; break; case 6: echo '游轮'; break; } ?>
We only need to make simple modifications to the above code to implement a simple housework dice and rock-paper-scissors game we play on WeChat. Think about it?
You can try it again:
We can remove the break in the case 1 code segment. Try it again. What is the effect?
## Let’s write a simple week judgment. The writing method can also be a little weird:
<?php //得到今天是星期几的英文简称 $day = date('D'); switch($day){ //拿学校举例,我们让星期一、二、三是校长日 case 'Mon': case 'Tue': case 'Wed': echo '校长日'; break; echo '星期三'; break; case 'Thu': echo '星期四'; break; case 'Fri': echo '星期五'; break; default: echo '周末,周末过的比周一到周五还要累<br />'; }; ?>Try your own experiment:
The above example found that defaultk was executed when there was a mismatch, right?
<?php //用swith...case来完成bool判断 $bool=true; switch($bool){ case true: case false: } /*********分隔线*******************/ if($bool){ }else{ } ?>The most infatuated waiting in the world is that I am case and you are switch. I wait silently, but you don't choose me!