switch statement is wondrous and magic. It's a piece of the language that allows you to select between different options for a value, and run different pieces of code depending on which value is set.
Each possible option is given by a
case in the switch statement.
A simple switch statement
Delimiting code blocks
The major caveat of
switch is that each case will run on into the next one, unless you stop it with
break. If the simple case above is extended to cover case 5:
In the above example of fallthrough, the code for case 4 hasn't been terminated, so it's run on into the code for case 5.
$foo ends up as 34, and both messages get printed. The easiest way to stop this is by delimiting the blocks of code with
Using fallthrough for multiple cases
switch will keep running code until it finds a
break, it's easy enough to take the concept of fallthrough and run the same code for more than one case:
Multiple-case code blocks
In the above code, the code blocks for cases 2 and 3 are empty, and don't have a
break; this means that they'll immediately follow on to the code for case 4. In other words, all three cases will run the same code.
The default case
Most of the time, you'll want to run specific code for particular cases, and some kind of "normal situation" code for any other cases. Let's say that the code above deals with a value from 1 to 10; instead of filling in the six missing cases, we can simply give a
A default case
Advanced switching: Condition cases
switch doesn't just allow you to switch on the value of a particular variable: you can use any expression as one of the cases, as long as it gives a value for the
case to use. As an example, here's a simple validator written using
Validation with switching
switch is a powerful tool. Use it.