Switch statements in PHP

This tutorial explains how to use switch statements in the PHP language. Switch statements can have a number of possible execution paths, unlike if, else and else if statements. Switch statements can be used to test different conditions for a single variable and can be more efficient to write than if, else and else if statements.

If you find you are writing several if, else if, and else statements and you find your code is getting a little messy, then using a switch statement might be the cleaner, neater, and more efficient way to go.

 

A switch statement involves multiple cases that can be tested for a variable as well as a default case if no other conditions (cases) are met. Each case also has a break statement which means if the condition from one case is met, then the switch statement will end and none of the other cases will be tested. To see how to use switch statements in PHP, you can watch the video below or scroll down to see the sample code.

PHP Sample code:

Note how the break; statement is used below. When used, it can stop checking all other cases once a test case evaluates to true. It is optional and if left out, the program will continue to check all other cases and run their code if they evaluate to true, until the switch statement ends.

<?php
 
 $day = 300;
 
 switch($day){
 case 1:
 echo "Monday";
 break;
 
 case 2:
 echo "Tuesday";
 break;
 
 case 3:
 echo "Wednesday";
 break;
 
 case 4:
 echo "Thursday";
 break;
 
 case 5:
 echo "Friday";
 break;
 
 /* 
 Break statement is optional - when it is executed, it will stop
 the switch statement from running
 */
 
 // The default case is also optional.
 
 default:
 echo "Not a weekday";
 break;
 }
 
 
?>

PHP Manual references: