PHP Switch statement
The switch statement is used to perform different actions based on multiple different conditions.
PHP Switch Statement
If you want to selectively execute one of several blocks of code, use the switch statement.
Syntax
<?php switch(n){ //字符串,整型 case 具體值: 執(zhí)行代碼; break; case 具體值2: 執(zhí)行代碼2; break; case 具體值3: 執(zhí)行代碼3; break; default: ?>
Working principle: First perform a calculation on a simple expression n (usually a variable). Compares the value of the expression to the value of each case in the structure. If there is a match, the code associated with the case is executed. After the code is executed, use break to prevent the code from jumping to the next case to continue execution. The default statement is used to execute when there is no match (that is, no case is true).
The variables that need to be judged are placed after switch, and the results are placed after case. What is the variable value after switch? The case value is written in the same code segment as the switch variable.
? break is optional
? default is also optional, but as a good habit, it is recommended to retain the default statement
? case is followed by a semicolon, followed by Colon:
? The variable in switch is preferably an integer, string
? The expression of the switch statement must be equal to the judgment, and the case must be a clear value, so if there is For greater than or less than judgment, you can only use if and elseif, but not switch
If we use a flow chart to express it, the result will be as shown below:
Example
<?php $favcolor="red"; switch ($favcolor) { case "red": echo "你喜歡的顏色是紅色!"; break; case "blue": echo "你喜歡的顏色是藍(lán)色!"; break; case "green": echo "你喜歡的顏色是綠色!"; break; default: echo "你喜歡的顏色不是 紅, 藍(lán), 或綠色!"; } ?>
Try it?
<?php //定義出行工具 $tool=rand(1,6); switch($tool){ case 1: echo '司機(jī)開車'; break; case 2: echo '民航'; break; case 3: echo '自己家的專機(jī)'; break; case 4: echo '火車動(dòng)車'; break; case 5: echo '騎馬'; break; case 6: echo '游輪'; break; } ?>