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 具體值: 執(zhí)行代碼; break; case 具體值2: 執(zhí)行代碼2; break; case 具體值3: 執(zhí)行代碼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){ //拿學(xué)校舉例,我們讓星期一、二、三是校長日 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!