Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making use of a fall-through switch

While researching for better ways to make use of a switch statement, I found this stackoverflow example. I wanted to do something similar, but with a twist:

switch($status)
{
 case "a":
 case "b":
  echo "start execute code for case a and b";
 case "a":
  echo "continue to execute code for case a only";
 case "b":
  echo "continue to execute code for case b only";
 case "a":
 case "b":
  echo "complete code execution for case a and b";
 break;
 case "c":
  echo "execute code for case c";
 break;
 case "d":
  echo "execute code for case d";
 break;
 case "e":
  echo "execute code for case e";
 break;
 case "f":
  echo "execute code for case f";
 break;
 default:
  echo "execute code for default case";
}

Yes, the above obviously doesn't work out as planned because case "a" will fall-through through until it hits a break. I just want to know whether there is a way to do this elegantly without repeating too much code.

like image 387
Question Overflow Avatar asked Apr 06 '12 15:04

Question Overflow


1 Answers

Here is what I think would be an elegant solution:

switch($status)
{
 case "a":
 case "b":
  echo "start execute code for case a and b";
  if($status == "a") echo "continue to execute code for case a only";
  if($status == "b") echo "continue to execute code for case b only";
  echo "complete code execution for case a and b";
 break;
 case "c":
  echo "execute code for case c";
 break;
 case "d":
  echo "execute code for case d";
 break;
 case "e":
  echo "execute code for case e";
 break;
 case "f":
  echo "execute code for case f";
 break;
 default:
  echo "execute code for default case";
}

I am not trying to invent anything new here. Just trying to learn from the experiences of everyone here. Thanks to all who provided me with answers.

like image 89
Question Overflow Avatar answered Sep 30 '22 19:09

Question Overflow