The PHP switch Statement
When one value can lead to several different actions, a switch statement keeps them neatly organized. PHP uses it to pick one block of code out of many and run it.
Switch syntax
A switch statement is laid out like this:
<?php
switch (expression) {
case label1:
//code block
break;
case label2:
//code block
break;
case label3:
//code block
break;
default:
//code block
}
?>
How It Works
PHP works out the expression a single time, then compares the result with the value of each case in turn. When it finds a match, it runs the code for that case. Put a break at the end of each block, because without one PHP would carry on into the next case. If nothing matches, the default block runs instead.
Switch statement with colors
Depending on what $favcolor holds, a different message is printed. It is set to "red" here:
Output: PHP script
<?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 default Keyword
The default keyword marks the code to use when none of the cases match. Think of it as the else at the end of an if...elseif...else statement.
Switch with day of the week
This switch turns the day number from date("w") into the name of today's day:
Output: PHP script
<?php
$d = date("w");
switch ($d) {
case 0:
echo "Sunday";
break;
case 1:
echo "Monday";
break;
case 2:
echo "Tuesday";
break;
case 3:
echo "Wednesday";
break;
case 4:
echo "Thursday";
break;
case 5:
echo "Friday";
break;
case 6:
echo "Saturday";
break;
}
?>
Common Code Blocks
Several cases can share one code block. Stack them directly above each other and leave out the break between them. This technique is sometimes called fall-through.
Fall-through in switch
The "red" and "blue" cases are stacked, so either value leads to the same message:
Output: PHP script
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
case "blue":
echo "Your favorite color is either red or blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>