Extra Block Types (EBT) - New Layout Builder experience❗

Extra Block Types (EBT) - styled, customizable block types: Slideshows, Tabs, Cards, Accordions and many others. Built-in settings for background, DOM Box, javascript plugins. Experience the future of layout building today.

Demo EBT modules Download EBT modules

❗Extra Paragraph Types (EPT) - New Paragraphs experience

Extra Paragraph Types (EPT) - analogical paragraph based set of modules.

Demo EPT modules Download EPT modules

Scroll

PHP Lessons - Lesson 8-2 - The switch statement

16/04/2025, by Ivan

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 using case.
  • 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:

  1. Always use break; after each case to avoid unintended fall-through.
  2. You don’t need to use break; after default since it’s the last condition.

Here is a flowchart to visualize how switch works:

Switch flowchart

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;
}
?>