The switch
statement allows you to simplify our previously written if…elseif…else statement by not constantly writing out the condition to check for. So, let’s take our code:
And rewrite it in the form of a switch
statement.
This is how it works: First we have a single expression n (a variable in our case called $name
), that is evaluated once. The value of the expression is then compared with the values for each case in our switch statement. If there is a match, the block of code associated with that case is executed. If no match is found the default statement is used. break;
is used to separate the various case types.