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:
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:
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:
'; }; ?>Try your own experiment:
The above example found that defaultk was executed when there was a mismatch, right?