23 – PHP Switch


Last time, in my previous lesson we have learned about the If statement in PHP. But, when checking for certain conditions there are times that an if statement is not the most effective way.


For instance, there is a variable that contains  OOTD (Outfit of the day) for summer vacation and you want to prepare those clothes according to this OOTD (Outfit of the day) variable. In this example, you might have 30 variety of clothes that you would have to check with long codes of If/ElseIf/ElseIf/ElseIf/… statements. This may sound complicated and not fun to code well, let’s see what we can do to make things easier.


php switch statement: Checking Quickly

The switch statement is the most efficient way to check all conditions at once. Instead, of checking the variable one at a time as it goes through a lot of if statements, it only takes a single variable to check all variety cases you set up for that switch statement. That’s the great thing about switch statement.


In our example, the single variable will be $OOTD and the cases will be? Monday, Tuesday, Wednesdays, Thursday, and Friday.

PHP Code-Switch Statement:


What clothes to wear on Thursday
Wear folded polo shirt and jeans

The value of $OOTD was Thursday, so when PHP performed the switch operating on $OOTD it immediately did a search for a case with the value of “Thursday“. It searches for it and moved to execute the code that existed within that segment.


You will see that there’s a break at the end of the codes. Well, this break simply stops other cases from being performed. If the break statement is not used in the above example all other cases that follow Thursday will be executed too. So, you have to take note most especially for newbie programmers to avoid confusions when using switch statements.


php switch statement: default

It is very important that to have a default in a conditional statement. For instance, if the variable does not match to the condition that is where you use the default statement. The if statementit has an else for the default and the switch statement also has a default case for the default.

Reminder:  its not necessary to use the word case you can directly use the keyword default.

PHP Code-Switch Statement with default case:


Traveling to New York
Wear underwear only!


Looking for more source code? Type your keyword here here!


Please enter your comment!
Please enter your name here

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