The switch
statement in PHP is used when you need to compare one variable with multiple values. It provides a cleaner alternative to using multiple if-elseif
statements.
🛠 Syntax of Switch Statement
switch (variable) { case value1: // Code to execute if variable == value1 break; case value2: // Code to execute if variable == value2 break; default: // Code to execute if no case matches }
📝 Example 1: Basic Switch Statement
Check the day of the week using a switch statement.
<?php $day = "Tuesday"; switch ($day) { case "Monday": echo "Start of the work week!"; break; case "Friday": echo "Weekend is near!"; break; case "Sunday": echo "It's a relaxing day!"; break; default: echo "It's a regular weekday."; } ?>
📝 Example 2: Switch with Numbers
Determine a grade based on a numeric score.
<?php $score = 85; switch (true) { case ($score >= 90): echo "Grade: A"; break; case ($score >= 80): echo "Grade: B"; break; case ($score >= 70): echo "Grade: C"; break; default: echo "Grade: F"; } ?>
🎯 Quick Summary
switch
→ Compares a variable against multiple cases.case
→ Defines a possible value to match.break
→ Exits the switch after a match is found.default
→ Executes if no case matches.
📝 Practice Time!
Try modifying the examples and see how the switch
statement works in different scenarios. Keep experimenting! 🚀