If you want only the code in the matching block to execute, place a break keyword at the end of that block. When PHP comes across the break keyword, processing jumps to the next line after the entire switch statement. Example 4-11 illustrates how processing works with no break statements.
Example 4-11. What happens when there are no break keywords
$action = "ASSEMBLE ORDER"; switch ($action) { case "ASSEMBLE ORDER": echo "Perform actions for order assembly.<br />"; case "PACKAGE": echo "Perform actions for packing.<br />"; case "SHIP": echo "Perform actions for shipping.<br />"; }
If the value of $action is "ASSEMBLE ORDER", the result is:
Perform actions for order assembly. Perform actions for packing. Perform actions for shipping.
However, if a user has already assembled an order, a value of "PACKAGE" produces the following:
Perform actions for packing. Perform actions for shipping.
Defaulting
The SWITCH statement also provides a way to do something if none of the other cases matches, which is similar to the else statement in an if, elseif, or else block.
Use the DEFAULT: statement for the SWITCH's last case statement (see Example 4-12).
Example 4-12. Using the DEFAULT: statement to generate an error
switch ($action) { case "ADD": echo "Perform actions for adding."; break; case "MODIFY": echo "Perform actions for modifying."; break; case "DELETE": echo "Perform actions for deleting."; break; default: echo "Error: Action must be either ADD, MODIFY, or DELETE."; }
The switch statement also supports the alternate syntax in which the switch and endswitch keywords define the start and end of the switch instead of the curly braces {}, as shown in Example 4-13.
Example 4-13. Using endswitch to end the switch definition
switch ($action): case "ADD": echo "Perform actions for adding."; break; case "MODIFY": echo "Perform actions for modifying."; break; case "DELETE": echo "Perform actions for deleting."; break; default: echo "Error: Action must be either ADD, MODIFY, or DELETE."; endswitch;
You've learned that you can have your programs execute different code based on conditions called expressions. The switch statement provides a convenient format for checking the value of an expression against numerous possible values.