Home  >  Article  >  Backend Development  >  Detailed explanation of PHP's switch function (working principle)

Detailed explanation of PHP's switch function (working principle)

藏色散人
藏色散人forward
2021-03-15 18:06:554813browse

The switch statement is a flow control statement in PHP. This article will take you through the switch statement and how to use it. I hope it will be helpful to you!

Detailed explanation of PHP's switch function (working principle)

Recommended: "PHP Video Tutorial"

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

Switch Statement

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

Use the Switch statement to avoid lengthy if..elseif..else code blocks.

Grammar

switch (expression)
{
case label1:
  expression = label1 时执行的代码 ;
  break;  
case label2:
  expression = label2 时执行的代码 ;
  break;
default:
  表达式的值不等于 label1 及 label2 时执行的代码;
}

Working principle:

1. Perform a calculation on the expression (usually a variable)
2. Compare the value with the value of case in the structure
3. If there is a match, execute the code associated with the case
4. After the code is executed, the break statementprevents the code from jumping to the next case Continue execution in
5. If no case is true, use the default statement

Example

<?php
$favfruit="orange";

switch ($favfruit) {
   case "apple":
     echo "Your favorite fruit is apple!";
     break;
   case "banana":
     echo "Your favorite fruit is banana!";
     break;
   case "orange":
     echo "Your favorite fruit is orange!";
     break;
   default:
     echo "Your favorite fruit is neither apple, banana, or orange!";
}
?>

The above is the detailed content of Detailed explanation of PHP's switch function (working principle). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete
Previous article:"Clone Sheep" in phpNext article:"Clone Sheep" in php