Home >Backend Development >PHP Tutorial >PHP: Detailed explanation of simple examples of switch statement usage

PHP: Detailed explanation of simple examples of switch statement usage

伊谢尔伦
伊谢尔伦Original
2017-06-24 10:42:352091browse

Standard syntax of switch statement in PHP:

switch (expression)
{
case label1:
 code to be executed if expression = label1;
 break;
case label2:
 code to be executed if expression = label2;
 break;
default:
 code to be executed
 if expression is different from both label1 and label2;
}

Example:

switch($i){
  case 1:
    echo 1;
    break;
  case 2:
    echo 2;
    break;
  default:
    echo 'others';
}

You can also use switch to determine a value range, or in a case Custom conditions.

<?php
header("content-type:text/html;charset=utf8");
$score=50;
switch($score)
{
 case $score>=90 && $score<=100:
  echo "优<br>";
  break;
 case $score>=80 && $score<90:
  echo "良<br>";
  break;
 case $score>=70 && $score<80:
  echo "中<br>";
  break;
 case $score>=60 && $score<70:
  echo "及格<br>";
  break;
 case $score>=0 && $score<60:
  echo "不及格<br>";
  break;
 default:
  echo"成绩输入错误<br>";
}
?>

The system calculates the value of expr and selects the corresponding execution statement below based on the calculation results (result1, result2, etc.). If all case results are not consistent, the statement in default will be executed.

<?php
switch ($x) {
  case 0:
  echo "x 等于 0";
  break;
  case 1:
  echo "x 等于 1";
  break;
  case 2:
  echo "x 等于 2";
  break;
  default:
  echo "x 既不等于1和2,也不等于0";
}
?>

Tips

•There can be multiple cases Conditional judgment

•The result after the case is not limited to numbers, but can also be characters or other Types supported by PHP

•default is not required

The above is the detailed content of PHP: Detailed explanation of simple examples of switch statement usage. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn