PHP Switch Statement
The PHP Switch Statement tutorial explains how to use a super if statement, a switch statement.
The PHP switch statement is pretty much a simplified way to write multiple if statements for one variable. As you use them, you will begin to realize why they are much more convenient that writing a whole lot of if statements or elseif statements. If statements check one conditional, but switch statements can check for many different cases. The simple syntax of switch statements provide more readable code as opposed to using a lot of else if statements.
The syntax is slightly different than an if statement. The entire switch is implicitly using the == that we saw in the if statements earlier. However, we can see that we do not have to repeat that boring comparison operator over and over. Instead, the case is followed by the conditional variable. After the case 1, we see a :. After that colon, we have our statements to be executed. Finally, we come to the break, which signals the end of the if like statement. If we didn't use break, PHP would continue to execute the other conditions in the switch statement. So, use break at the end of your case block to break out of the switch statement unless you want the following cases to be executed. As for the default:, it means that if none of the other conditions are satisfied, do the statements following the default:. The default term is comparable to the else statement.
Try testing your code with the code simulator!
Let's move on to some more tutorials or the next section!