PHP Lessons - Lesson 8-2 - The switch statement
In the previous lesson, we learned about the if
statement. The if
statement allows us to check a condition and execute specific actions based on the result.
Now imagine you need to perform ten different checks and execute different actions based on each result. Sure, you could write this using multiple if
statements:
<?php if ($x == 1) { // action } if ($x == 2) { // action } ... if ($x == 10) { // action } ?>
This method works, but it’s more efficient and readable to use a switch
statement.
PHP switch
The switch
statement lets you check a value against multiple possible cases. Here's the same example using switch
:
<?php switch ($x) { case 1: // action break; case 2: // action break; ... case 10: // action break; default: // action if no case matched } ?>
As mentioned earlier, both approaches work the same. But with switch
, we added a default
case which runs if none of the other cases match the value of $x
.
Let’s break down how switch
works:
- The
switch
keyword is followed by the variable or expression to evaluate. - Inside the curly braces
{ }
, each possible value is handled usingcase
. - If the value of the expression matches a
case
, the code in that block is executed. - Use
break;
to stop further execution of the switch cases. - The
default
case executes if no other case matches (optional).
You can also use switch
with string values:
<?php switch ($x) { case 'Hello': // action break; case 'Bye': // action break; } ?>
Important reminders:
- Always use
break;
after each case to avoid unintended fall-through. - You don’t need to use
break;
afterdefault
since it’s the last condition.
Here is a flowchart to visualize how switch
works:
Example: Calculating the day of the week based on the number of days since Monday:
<?php // $D is the number of days since Monday $x = $D % 7; switch ($x) { case 1: print 'Monday'; break; case 2: print 'Tuesday'; break; case 3: print 'Wednesday'; break; case 4: print 'Thursday'; break; case 5: print 'Friday'; break; case 6: print 'Saturday'; break; case 0: print 'Sunday'; break; } ?>