Search

PHP Switch Statement

The PHP switch statement is similar to a series of IF statements on the same expression.

The following two examples are two different ways to write the same thing, one using a series of PHP if and else if statements, and the other using the PHP switch statement:

PHP switch statement Use to select one of many blocks of code to be executed . and this is similar to a series of IF statements on the same expression.

Syntax

switch (n) {
  case label1:
    code to be executed if n=label1;
    break;
  case label2:
    code to be executed if n=label2;
    break;
  case label3:
    code to be executed if n=label3;
    break;
    ...
  default:
    code to be executed if n is different from all labels or not match any case ;
}

Example

<?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;
       default:
    echo "This is not 0 , 1, 2";
}
?>

switch

The PHP switch keyword is used to create a switch conditional. switch condition choose a block of code to run based on the value of an expression or condition.

case

The PHP case keyword is used to jump to a line of code when an expression has a specific value in a switch condition.

break

The PHP break keyword is used to break out of for loops, foreach loop, while loop, do..while loops and switch conditions.

default

The PHP default keyword is used in a PHP switch block to specify which code to run when none of the case statements were matched by the expression.

Stack Overlode is optimized Tutorials and examples for learning and training. Examples might be simplified to improve reading and learning and understand. Tutorials and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using Stack Overlode, you agree to have read and accepted our terms of use, cookie and privacy policy.