switch statemen...LOGIN

switch statement

PHP Switch Statement

If you want 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).

Example

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

Multi-way branch structure

1. In switch() brackets, it must be a variable

2.In switch(){} The most common ones in China are case statements, case spaces, followed by values, and a colon after the value:

switch(变量){
                   case 值:
                                     语句;
                                     语句;
                                     语句;
                               语句;
                                     break;
                   case 值2:
                                     语句;
                                     break;
                   case 值3:
                                     语句;
                                     break;
                   .......
}

switch-case Some details to pay attention to:

1. If in If there are too many statements in the case, you need to make multiple statements into a function or the like

2switch (variable) variable type, the value allows two types: integer and string.

3.break is used to exit the switch structure. If you need to match multiple values ​​at the same time, you can use multiple cases without adding break.

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