Can expressions be used in PHP switch?

(*-*)浩
Release: 2023-02-26 17:56:02
Original
2292 people have browsed it

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;
}
?>
Copy after login

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;
}
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template