The switch-case statements are used to test an expression with different values.
The switch-case statement is an alternative to the if-elseif-else statement, which does almost the same thing. The switch-case statement tests a variable against a series of values until it finds a match, and then executes the block of code corresponding to that match.
Syntax:
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
}
Example:
<?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-casestatement differs from theif-elseif-elsestatement in one important way. Theswitchstatement executes line by line (i.e. statement by statement) and once PHP finds acasestatement that evaluates to true, it’s not only executes the code corresponding to that case statement, but also executes all the subsequentcasestatements till the end of theswitchblock automatically.To prevent this add a
breakstatement to the end of eachcaseblock. Thebreakstatement tells PHP to break out of theswitch-casestatement block once it executes the code associated with the first true case.
This is the tutorial on how to use PHP Switch Case Statements.
If you have any question, feel free to ask it at our Forum Section.