Skip to content

How to Make Switch-Case Smaller and Smarter

In the following example, there are only four possible outputs represent four quarters in the switch-case.

<?php
$month = "4";
...
switch ($month) {
  case "1" :
    echo "1st quarter.";
    break;
  case "2" :
    echo "1st quarter.";
    break;
  case "3" :
    echo "1st quarter.";
    break;
  case "4" :
    echo "2nd quarter.";
    break;
  case "5" :
    echo "2nd quarter.";
    break;
  case "6" :
    echo "2nd quarter.";
    break;
  case "7" :
    echo "3rd quarter.";
    break;
  case "8" :
    echo "3rd quarter.";
    break;
  case "9" :
    echo "3rd quarter.";
    break;
  case "10" :
    echo "4th quarter.";
    break;
  case "11" :
    echo "4th quarter.";
    break;
  case "12" :
    echo "4th quarter.";
    break;
  default :
    echo "no indication";
    break;
}
?>

The output is:

2nd quarter.

It's a little tedious to code such switch-case blocks. Here I recommend 3 ways to make the block of code smaller if you insist to use switch-case clause.

Fall Through

<?php
$month = "4";
switch ($month) {
  case "1" :
  case "2" :
  case "3" :
    echo "1st quarter.";
    break;
  case "4" :
  case "5" :
  case "6" :
    echo "2nd quarter.";
    break;
  case "7" :
  case "8" :
  case "9" :
    echo "3rd quarter.";
    break;
  case "10" :
  case "11" :
  case "12" :
    echo "4th quarter.";
    break;
  default :
    echo "no indication";
    break;
}
?>

Logical Expression

<?php
$month = "4";
switch (true) {
  case $month == "1" || $month == "2" || $month == "3" :
    echo "1st quarter.";
    break;
  case $month == "4" || $month == "5" || $month == "6" :
    echo "2nd quarter.";
    break;
  case $month == "7" || $month == "8" || $month == "9" :
    echo "3rd quarter.";
    break;
  case $month == "10" || $month == "11" || $month == "12" :
    echo "4th quarter.";
    break;
  default :
    echo "no indication";
    break;
}
?>

Regular Expression

<?php
$month = "4";
switch (true) {
  case preg_match('/^0?[1-3]$/',$month) :
    echo "1st quarter.";
    break;
  case preg_match('/^0?[4-6]$/',$month) :
    echo "2nd quarter.";
    break;
  case preg_match('/^0?[7-9]$/',$month) :
    echo "3rd quarter.";
    break;
  case preg_match('/^1[012]$/',$month) :
    echo "4th quarter.";
    break;
  default :
    echo "no indication";
    break;
}
?>

Of course, you can use if-elseif-else to rewrite the code, but sometimes you can't. IMHO, I like the way of fall-through which is a very nice feature in switch-case clause and easy to understand. The way of regular expression may fit more complicated scenarios.

Leave a Reply

Your email address will not be published. Required fields are marked *