Easy Tutorial
❮ Pdostatement Fetchcolumn Php Preg_Match_All ❯

PHP Switch Statement


The switch statement is used to perform different actions based on different conditions.


PHP Switch Statement

If you want to selectively execute one of multiple code blocks, use the switch statement.

Syntax

<?php
switch (n)
{
case label1:
    code to be executed if n = label1;
    break;
case label2:
    code to be executed if n = label2;
    break;
default:
    code to be executed if n is different from both label1 and label2;
}
?>

How it works: First, a single expression n (usually a variable) is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the code associated with that case is executed. After the code is executed, break is used to prevent the code from falling through to the next case. The default statement is used to execute code if there is no match (i.e., no case is true).

Example

<?php
$favcolor = "red";
switch ($favcolor)
{
case "red":
    echo "Your favorite color is red!";
    break;
case "blue":
    echo "Your favorite color is blue!";
    break;
case "green":
    echo "Your favorite color is green!";
    break;
default:
    echo "Your favorite color is neither red, blue, nor green!";
}
?>
❮ Pdostatement Fetchcolumn Php Preg_Match_All ❯