PHP Switch Statements. Everything You Need To Know About Switch In PHP

Posted by TotalDC

Now that we covered IF – ELSE statements in this article and now it’s perfect time to take a look at switch statements in PHP.

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 that the switch statement executes line by line and once it finds a case that evaluates to true it’s 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 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.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: