PHP Switch Case Statement
While Else If condition used for checking more than two conditions, almost switch case statement is used for checking more than two conditions but, switch case statement works with different actions and different conditions.
ElseIf statement works with the same action and different conditions.
Syntax of the switch case statement
switch (m) {
case data 1:
if data 1 = m, execute statement : 1;
break;
case data 2:
if data 2 = m, execute statement : 2;
break;
:
:
case data n:
if data n = m, execute statement : n;
break;
default:
if m didn't match from any data, execute this statement;
}
Understand the switch case statement from this example :
<?php
$m = "Wednesday";
switch ($m)
{
case "Monday":
echo "It's Monday";
break;
case "Tuesday":
echo "It's Tuesday";
break;
case "Wednesday":
echo "It's Wednesday";
break;
default:
echo "Something wrong!";
}
?>
Output:
It's Wednesday
Understand this through this example:
<?php
$m = "wednesday";
switch ($m)
{
case "Monday":
echo "It's Monday";
break;
case "Tuesday":
echo "It's Tuesday";
break;
case "Wednesday":
echo "It's Wednesday";
break;
default:
echo "Something wrong!";
}
?>
Output:
Something wrong!
Explanation:
In the previous example, we provided "Wednesday" as an argument in the switch case condition matched with the third case their case value given is "Wednesday".
But in the second example, we provided "wednesday" as an argument but this text didn't match with any case so It goes to the default condition.