The switch
structure performs the same function as a series of if
statements, but can do the job in fewer lines of code. The value to be tested, as defined in the switch
statement, is compared for equality with the values in each of the case
statements until a match is found and the code in that block is executed. If no matching case
statement is found, the code in the default
block is executed, if it exists.
Each block of code in a case
or default
statement should end with the break
statement. This stops the execution of the switch
structure and continues code execution immediately afterwards. If the break
statement is omitted, the next case
statement's code is executed, even if there is no match. This can cause unexpected code execution if the break
statement is forgotten, but can also be useful where multiple case
statements need to share the same code.
switch ($colour) {
case "red":
echo "the colour is red";
break;
case "green":
case "blue":
echo "the colour is green or blue";
break;
case "yellow":
echo "the colour is yellow";
// note missing break, the next block will also be executed
case "black":
echo "the colour is black";
break;
default:
echo "the colour is something else";
break;
}
In addition to testing fixed values, the construct can also be coerced to test dynamic statements by providing a boolean value to the switch
statement and any expression to the case
statement. Keep in mind the first matching value is used, so the following code will output "more than 100":
$i = 1048;
switch (true) {
case ($i > 0):
echo "more than 0";
break;
case ($i > 100):
echo "more than 100";
break;
case ($i > 1000):
echo "more than 1000";
break;
}
For possible issues with loose typing while using the switch
construct, see Switch Surprises