Home  >  Article  >  Backend Development  >  Can expressions be used in PHP switch?

Can expressions be used in PHP switch?

(*-*)浩
(*-*)浩Original
2019-10-15 13:14:452301browse

A switch statement is similar to a series of if statements with the same expression. In many cases, it is necessary to compare the same variable (or expression) with many different values, and execute different codes depending on which value it is equal to. This is exactly what the switch statement is for.

Can expressions be used in PHP switch?

Note:

Note that unlike other languages, the continue statement acts similarly to break when applied to switch. If you have a switch within a loop and want to continue to the next iteration in the outer loop, use continue 2. (Recommended learning: PHP Video Tutorial)

The following two examples use two different methods to achieve the same thing. One uses a series of if and elseif statements, and the other uses switch statement:

switch structure

<?php
if ($i == 0) {
    echo "i equals 0";
} elseif ($i == 1) {
    echo "i equals 1";
} elseif ($i == 2) {
    echo "i equals 2";
}

switch ($i) {
    case 0:
        echo "i equals 0";
        break;
    case 1:
        echo "i equals 1";
        break;
    case 2:
        echo "i equals 2";
        break;
}
?>

case expression can be any expression that evaluates to a simple type, that is, an integer or floating point number and a character string. Arrays or objects cannot be used unless they are dereferenced to simple types.

Can be rated:

$var = 95;
switch(true){
      case $var < 100;
          $level = 1;
          break;
      case $var < 95;
          $level = 2;
          break;
      default :
      $level=9; break;
}

The above is the detailed content of Can expressions be used in PHP switch?. 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