PHP Switch statement

The switch statement is used to perform different actions based on multiple different conditions.

PHP Switch Statement

If you want to selectively execute one of several blocks of code, use the switch statement.

Syntax

<?php
switch(n){   //字符串,整型 
  case 具体值: 
    执行代码; 
    break; 
  case 具体值2: 
    执行代码2; 
    break; 
  case 具体值3: 
    执行代码3; 
    break; 
default: 
?>

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 variables that need to be judged are placed after switch, and the results are placed after case. What is the variable value after switch? The case value is written in the same code segment as the switch variable.

• break is optional

• default is also optional, but as a good habit, it is recommended to retain the default statement

• case is followed by a semicolon, followed by Colon:

• The variable in switch is preferably an integer, string

• The expression of the switch statement must be equal to the judgment, and the case must be a clear value, so if there is For greater than or less than judgment, you can only use if and elseif, but not switch

If we use a flow chart to express it, the result will be as shown below:

103.png

Example

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

Try it»

<?php
//定义出行工具
$tool=rand(1,6);
switch($tool){
    case 1:
        echo '司机开车';
        break;
    case 2:
        echo '民航';
        break;
    case 3:
        echo '自己家的专机';
        break;
    case 4:
        echo '火车动车';
        break;
    case 5:
        echo '骑马';
        break;
    case 6:
        echo '游轮';
        break;
}
?>


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