PHP Switch…Case

PHP If...Else Vs Switch...Case

The switch-case statement serves as an alternative to the if-elseif-else statement, performing similar tasks. It checks a variable against a series of values until it finds a match, then executes the corresponding block of code.

switch(n){
    case label1:
        // Code executed if n=label1
        break;
    case label2:
        // Code executed if n=label2
        break;
    ...
    default:
        // Code executed if n doesn't match any labels
}

For instance, consider this example that displays a different message for each day.

<?php
$today = date("D");
switch($today){
case "Mon":
echo "Today is Monday. Clean your house.";
break;
case "Tue":
echo "Today is Tuesday. Buy some food.";
break;
case "Wed":
echo "Today is Wednesday. Visit a doctor.";
break;
case "Thu":
echo "Today is Thursday. Repair your car.";
break;
case "Fri":
echo "Today is Friday. Party tonight.";
break;
case "Sat":
echo "Today is Saturday. Its movie time.";
break;
case "Sun":
echo "Today is Sunday. Do some rest.";
break;
default:
echo "No information available for that day.";
break;
}
?>

The switch-case statement differs from the if-elseif-else statement in a crucial aspect. The switch statement executes line by line (statement by statement). Once PHP finds a case statement that evaluates to true, it executes the corresponding code and continues to execute all subsequent case statements until the end of the switch block.

To prevent this behavior, you can add a break statement at the end of each case block. The break statement instructs PHP to exit the switch-case block immediately after executing the code associated with the first true case.