PHP Switch Statement

The switch statement is used to make a decision from the number of choices is called a switch-case-default. The switch statement is the same as a series of IF statements on the same expression.

Syntax

<?php
switch (n) {
case condition1:
code to be executed if n=condition1;
break;
case condition2:
code to be executed if n=condition2;
break;
case condition3:
code to be executed if n=condition3;
break;
...
default:
code to be executed if n is different from all labels;
}
?>

Example:

In the following example, $color is equal to green, therefore the switch statement executes the third echo statement.

<?php
$color = "green";

switch ($color) {
    case "yellow":
        echo "color is yellow!";
        break;
    case "blue":
        echo "color is blue!";
        break;
    case "green":
        echo "color is green!";
        break;
    default:
        echo "color is neither yellow, blue, nor green!";
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*

*