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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With