Home >Backend Development >PHP Tutorial >How to implement switch statement in PHP to match multiple values in the same code block
switch Statements are executed line by line (actually statements after statements). Here is an introduction to php switch statementMultiple values match the same Code block
Let’s talk about the format of the switch() statement first
switch(expression){
case match 1:
When matching 1 and the expression match the successfully executed code;
break;
case match 2:
When the match 2 and the expression match the successfully executed code;
break ;
default:
Code executed if the case statement does not match the expression successfully;
}
It is very important to understand how switch is executed. The switch statements are executed line by line (actually statement by statement). Initially no code is executed. Only when the value in a case statement matches the value of the switch expression will PHP start executing the statement until the end of the switch block or until the first break statement is encountered. If you do not write break at the end of the statement segment of the case, PHP will continue to execute the statement segment in the next case.
Example:
<?php switch($i){ case 1: echo "$i的值是1"; break; case 2: echo "$i的值是2"; break; case 3: echo "$i的值是3"; break; default: echo "$i的值不是1、2、3"; } ?>
The statements in one case can also be empty, which only transfers control to the statements in the next case until the statement block of the next case is not empty, so that Implemented multiple value matching agreement code blocks:
Output the same statement when the value of $i is 1 or 2 or 3:
The code is as follows:
<?php switch($i){ case 1: case 2: case 3: echo "$i的值为$i的值为1或2或3"; break; } ?>
The above is the detailed content of How to implement switch statement in PHP to match multiple values in the same code block. For more information, please follow other related articles on the PHP Chinese website!