An expression that can be used only when you want to check one or more equations. The same thing you can do with the switch can be done with else if, but if you want to use an expression only when comparing one or more equations, the switch is more suitable for this operation.
<?php
// when we want to do with if:
if ($fruit === 'watermelon') {
echo 'watermelon selected';
} else if ($fruit === 'strawberry') {
echo 'strawberry selected';
} else if ($fruit === 'pear') {
echo 'pear selected';
}
// let's do the same with the switch:
switch ($fruit) {// express the variable to compare
case 'watermelon': // if it is equal to watermelon
echo 'watermelon selected';
break; // continue comparison if this option matches
case 'strawberry':
echo 'strawberry selected';
break;
case 'pear':
echo 'pear selected';
break;
}
?>
In such cases, using a switch is faster and shorter than using if.
You can compare more than one value by using the case expression one under the other.
<?php
switch ($fruit) {
case 'cherry':
case 'strawberry':
case 'watermelon':
echo 'fruit of red color';
break;
case 'pear':
echo 'yellow fruit';
break;
}
?>
If there is anything you want to do when it does not match any value expressed in the switch, we express it with βdefaultβ;
<?php
switch ($fruit) {
case 'banana':
echo 'we have bananas!';
break;
case 'watermelon':
echo 'there is watermelon!';
break;
default:
echo 'there is no this fruit!';
break;
}
?>