PHP Switch stat...LOGIN

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,此处代码将执行;
         break;
case label2:
         如果 n=label2,此处代码将执行;
         break;
default:
         如果 n 既不等于 label1 也不等于 label2,此处代码将执行;
}

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;

}

QQ图片20161008174304.pngQQ图片20161008174319.png

Instance

<?php
 $favcolor="red";
 switch ($favcolor)
 {
 case "red":
     echo "你喜欢的颜色是红色!";
     break;
 case "blue":
     echo "你喜欢的颜色是蓝色!";
     break;
 case "green":
     echo "你喜欢的颜色是绿色!";
     break;
 default:
     echo "你喜欢的颜色不是 红, 蓝, 或绿色!";
 }
 ?>


Next Section
<?php $favcolor="red"; switch ($favcolor) { case "red": echo "你喜欢的颜色是红色!"; break; case "blue": echo "你喜欢的颜色是蓝色!"; break; case "green": echo "你喜欢的颜色是绿色!"; break; default: echo "你喜欢的颜色不是 红, 蓝, 或绿色!"; } ?>
submitReset Code
ChapterCourseware