PHP Switch statement
PHP Switch Statement
The switch statement is used to perform different actions based on multiple different conditions.
PHP Switch Statement
If you wish to selectively execute one of several blocks of code, use the switch statement .
Syntax
switch (n) { case label1: 如果 n=label1,此處代碼將執(zhí)行; break; case label2: 如果 n=label2,此處代碼將執(zhí)行; break; default: 如果 n 既不等于 label1 也不等于 label2,此處代碼將執(zhí)行; }
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 switch statement is similar to a series of if statements with the same expression
Each case will be judged in turn whether expr and expr1..n are equal. If they are equal, Then execute the corresponding statement. If there is a break at the end, the switch statement will jump out after the execution is completed.
default is the default operation performed when all cases cannot be satisfied. The following example:
switch (expr)
{
case expr1:
statement;
break;
case expr2:
statement;
break;
……
default:
statement;
}
Instance
<?php $favcolor="red"; switch ($favcolor) { case "red": echo "你喜歡的顏色是紅色!"; break; case "blue": echo "你喜歡的顏色是藍色!"; break; case "green": echo "你喜歡的顏色是綠色!"; break; default: echo "你喜歡的顏色不是 紅, 藍, 或綠色!"; } ?>