You are not logged in.
Login or Register

Tip: Convert an if/elseif/else statement into a switch/case

Posted By: apeiro

Sometimes a switch statement can be neater than a bunch of if/elseif/else lines. Here's a simple way to do it.

In a typical switch statement, you create multiple cases for a single variable. But it's possible and syntactically-legal to use a boolean constant such as true for your switch variable. Then each case can be a boolean statement that must evaluate to true to trigger the case.

Example (if/elseif/else):

if($a && $b) {
  func1();
} else if($a && $c) {
  func2();
} else if($b && $c) {
  func3();
} else if($c) {
  func4();
} else {
  func5();
}

Now, converted into a switch statement:

switch(true) {
  case $a && $b: func1(); break;
  case $a && $c: func2(); break;
  case $b && $c: func3(); break;
  case $c:       func4(); break;
  default:       func5();
}

Much more readable!