Signup/Sign In

PHP Switch Statement

You must have used a lift which is used to go up and down a building, all you have to do is press the button with the floor number where you want to go, or a TV remote, using which you can change the channel on your TV just by selecting that channel number on the TV remote.


The switch statement

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

Using a switch statement, we can specify multiple conditions along with the code to be executed when that condition is true, thereby implementing a menu style program.

Syntax:

switch(X)
{
    case value1:
        // execute this code when X=value1
        break;
    case value2:
        // execute this code when X=value2
        break;
    case value3:
        // execute this code when X=value3
        break;
    ...
    default:
        /* execute this when X matches none of
           of the specified options */
}

You can specify as many options as you want using a single switch code block.

X can be a variable or an expression.

In a switch statement, we provide the deciding factor which can be a variable or an expression to our switch statement, and then we specify the different cases, each with a value, a piece of code and a break statement.

break statement is specified to break the execution of the switch statement once the action related to a specified value has been performed.

If we do not specify a break statement, then all the switch cases, after the matched case, will get executed, until the next break statement.

The default statement is executed if no matching case is there.

<?php
$car = "Jaguar";

switch($car)
{
    case "Audi":
        echo "Audi is amazing";
        break;
    case "Mercedes":
        echo "Mercedes is mindblowing";
        break;
    case "Jaguar":
        echo "Jaguar is the best";
        break;
    default:
        echo "$car is Ok";
}
?>

Jaguar is the best