PHP Programming/The switch Structure

How they work
Here's an example of a simple game where a user enters a $user_command and different functions are run as a result:

Clearly, there's a lot of repeated code here. The switch case structure allows you to avoid this redundant code. It allows programmers to repeatedly compare the value of a certain variable to a list of possible values and execute code based on the result. This is the syntax for a switch case statement, compared to the same code written using if statements:

The switch case style will save you from retyping $firstvariable, and make your code look cleaner (especially, if that code is a long chain of simple if statements). Returning to our zorkmid sample program, we have:

Syntax
In this example, $var is the first variable to be compared. This variable is then compared against each case statement from the top down, until it finds a match. At that point, the code will execute until a break statement is reached (that will allow you to leave the case statement entirely).

Important warning about using switch case statements
Don't forget to use break when you mean break! If you forget, you might run functions you don't intend to. However, there are circumstances where leaving breaks out can be useful. Consider this example:

This kind of coding is sometimes frowned upon, since it's not always as clear to see what the code is meant to do. Also, consider commenting case statements that aren't supposed to have a break; statement before the next case, so when others look at your code, they know not to add a break. In such a case, it is good programming practice to add comments to breakless cases so that it is clear that the break has been omitted deliberately:

For more information

 * PHP Manual: SWITCH Control Structure