Everything You Need To Know About Switch In PHP
Posted by TotalDCNow that we covered IF – ELSE statements in this article and now it’s the perfect time to take a look at PHP switch statements.
IF – ELSE VS Switch In PHP
Just like you would imagine switch is an alternative to the if – else statement. It does almost the same thing. The switch statement tests a variable against a series of values until it finds a match and then executes the block of code corresponding to that match.
switch(n){
case 1:
// Code to be executed if n=1
break;
case 2:
// Code to be executed if n=2
break;
case 3:
// Code to be executed if n=3
break;
default:
// Code to be executed if n is different
}
The switch statement differs from the if – else statement in one important way the switch statement executes line by line and once it finds a case that evaluates to true it not only executes the code corresponding to that case statement but also executes all the subsequent case statements until the end of the switch block automatically.
You should add a break statement to the end of each case block to prevent this behavior. The break statement tells PHP to break out of the switch statement block once it executes the code associated with the first true case.