PHP Switch Statement Case Multiple Conditions
Switch Statement Case Multiple Conditions
PHP Switch Statement condition used in PHP where we need to perform different actions based on different conditions.
Switch statements are similar to a series of IF statements that use the same expression.
In many places when you developed your website, you may want to compare (one to another)
the same variable with many different values and execute a different piece of code depending on which value it equals to.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
switch (m) { case labe1: code to be executed if m=labe1; break; case labe2: code to be executed if m=labe2; break; case labe3: code to be executed if m=labe3; break; ... default: code to be executed if n is different from all labels; } |
Explanation
First, we have a single expression m (most often a variable), that is evaluated once.
The value of the expression is then compared with the values for each case in the structure.
If the condition matched, the block of code associated with that case is executed, and break to prevent the code from running into the next case automatically.
Finally, the default statement is used if no match is found in the conditions.
Switch Statement Case Multiple Conditions: Flowchart-

PHP Switch Example-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php $num=20; switch($num){ case 10: echo("number is equals to 10"); break; case 20: echo("number is equal to 20"); break; case 30: echo("number is equal to 30"); break; default: echo("number is not equal to 10, 20 or 30"); } ?> |
Finally Output:-
1 |
number is equal to 20 |
PHP If…Else Vs Switch…Case
Here, The switch-case statement is an alternative method to the if-elseif-else statement or Condition, which are the almost same thing.
The switch-case statement condition its tests a variable against a series of values until it finds a match,
after that executes the block of code corresponding to that match.
1 2 3 4 5 6 7 8 9 10 11 |
switch(n){ case label1: // Code to be executed if n=label1 break; case label2: // Code to be executed if n=label2 break; ... default: // Code to be executed if n is different from all labels } |
See the given Below Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?php $today = date("D"); switch($today){ case "Mon": echo "Today is Monday. Washing the Car and goes to drive."; break; case "Tue": echo "Today is Tuesday. Buy Cloths."; break; case "Wed": echo "Today is Wednesday. Visit Our Factory."; break; case "Thu": echo "Today is Thursday. Going to Lunch with Family In Night."; break; case "Fri": echo "Today is Friday. Watch movie show."; break; case "Sat": echo "Today is Saturday. going to temple."; break; case "Sun": echo "Today is Sunday. Rest with our Family and Enjoy."; break; default: echo "No task available for that day."; break; } ?> |
Resource
PHP.net