php Statement Implementation of multiple values matching the same code block

  • 2021-01-18 06:20:11
  • OfStack

Let's start with the format of the switch() statement

switch(expression){

case Match 1:
Code executed when match 1 and expression match successfully;
break;

case Match 2:
Code executed when Match 2 and expression match successfully;
break;
default:
The code executed if the case statement did not succeed with the expression;
}

It is important to understand how switch is implemented. switch statements are executed line by line (actually statement by statement). No code is executed at the beginning. Only when the value in an case statement matches the value in an switch expression does PHP execute the statement until either the end of the switch segment or the first break statement is encountered. If you do not write break at the end of a segment in case, PHP will continue to execute the next segment in case.
Example:
 
<?php 
switch($i){ 
case 1: 
echo "$i The value is 1"; 
break; 
case 2: 
echo "$i The value is 2"; 
break; 
case 3: 
echo "$i The value is 3"; 
break; 
default: 
echo "$i The value is not 1 , 2 , 3"; 
} 
?> 

The statement in one case can also be null, thus simply transferring control to the statement in the next case until the next case statement block is not null, thus implementing multiple value matching consent code blocks:
$i = 1; $i = 1; $i = 1; $i = 1;
 
<?php 
switch($i){ 
case 1: 
case 2: 
case 3: 
echo "$i The value of $i The value of 1 or 2 or 3"; 
break; 
} 
?> 

Related articles: