Application example of php switch statement with multiple values matching the same code block

  • 2021-07-10 18:58:51
  • OfStack

Let's talk about the format of switch () statement first

switch (expression) {

case Match 1:

Code executed successfully when match 1 and expression match;

break;

case Match 2:

Code executed successfully when match 2 and expression match;

break;

default:

If the case statement has no code executed with the successful expression;

}

It is important to understand how switch is implemented. The switch statement is executed line by line (statement by statement, in fact). No code is executed at the beginning. PHP starts executing a statement only when the value in an case statement matches the value of an switch expression until the segment of switch ends or the first break statement is encountered. If break is not written at the end of the statement segment of case, PHP will continue to execute the statement segment in the next case.

Examples:


<?php

switch($i){

case 1:

echo "$i The value of is 1";

break;

case 2:

echo "$i The value of is 2";

break;

case 3:

echo "$i The value of is 3";

break;

default:

echo "$i The value of is not 1 , 2 , 3";

}

?>

The statement in one case can also be empty, which only transfers control to the statement in the next case, knowing that the statement block in the next case is not empty, thus realizing multiple value matching consent code blocks:

Output the same 1 statement when the value of $i is 1 or 2 or 3:


<?php

switch($i){

case 1:

case 2:

case 3:

echo "$i The value of is $i The value of is 1 Or 2 Or 3";

break;

}
?>

Related articles: