Home » PHP » PHP Switch
This tutorial is on how to use a PHP Switch. Let's begin by understanding the basics of PHP switch.
You can use a switch statement to perform different actions on the basis of different conditions.
A switch statement can be used to specify multiple conditions along with the code to be executed when that condition is true, by that means 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 */
}
A single switch code block can be used to specify as many options as you want.
X can be an expression or a variable.
In a switch statement, you can provide a deciding factor, whether an expression or variable, to your switch statement. Then you can specify the different cases, each with a piece of code, value, and a break statement.
You can specify the break statement to break the execution of the switch statement after the action related to a specified value has been performed.
If a break statement is not specified, then all switch cases, after the matched case, will get executed till the next break statement.
If there is no matching case, then the default statement is executed.
<?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";
}
?>
Output:
Jaguar is the best