The switch
statement in PHP is used to perform different actions based on different conditions. It is an alternative to multiple if...elseif
statements, making code more readable and efficient.
switch (expression) {
case value1:
// Code to execute if expression == value1
break;
case value2:
// Code to execute if expression == value2
break;
default:
// Code to execute if no case matches
}
✔ The break
statement prevents execution from falling through to the next case.
✔ The default
case executes if no match is found (optional).
Example 1: Simple Switch Statement
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the workweek!";
break;
case "Friday":
echo "Weekend is near!";
break;
case "Sunday":
echo "Relax, it's the weekend!";
break;
default:
echo "It's just another day!";
}
✔ If $day = "Monday"
, output will be "Start of the workweek!"
$grade = 85;
switch (true) {
case ($grade >= 90):
echo "Grade: A";
break;
case ($grade >= 80):
echo "Grade: B";
break;
case ($grade >= 70):
echo "Grade: C";
break;
default:
echo "Grade: F";
}
✔ If $grade = 85
, output will be "Grade: B"
When to Use Switch?
✔ When checking one variable against multiple values
✔ When avoiding multiple if...elseif
statements
✔ When handling menu selections, user roles, or status codes
Conclusion
✔ switch
is useful for cleaner and more readable code.
✔ Use break
to prevent execution from falling through cases.
✔ default
runs when no cases match (optional). 🚀