The switch statement is used to perform different actions based on different conditions. It is a cleaner, more readable alternative to a long chain of if...elseif...else statements when you are comparing the same variable against many different values.
The switch statement evaluates an expression once. Its value is then compared with the values for each case in the block. If there is a match, the associated block of code is executed.
<?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!";
}
?>
The break keyword is used to stop the code from automatically running into the next case. Without break, PHP will continue executing all following cases even if they don't match (this is called "fall-through").
The default statement is used if no match is found. It acts like the final else in an if-else chain. It is not mandatory, but it's good practice to include it for error handling.
switch statement can be slightly faster than an if...elseif chain because the expression is only evaluated once.