Nested switch is an option ...
In this case, two switches are used, but the second does not start in the default case, so it has a slightly better performance profile than the two built-in switches.
switch($x) { case a: case b: case c: executeSth(); switch($x) { case a: executeA(); break; case b: executeB(); break; case c: executeC(); break; } break; default: ... }
Alternatively, a variable function can do the job ...
This is a variant of PHP that can work, although many people do not like variable functions. This is probably the best option if you want to completely remove nesting and repetition.
switch($x) { case a: $function = "executeA"; break; case b: $function = "executeB"; break; case c: $function = "executeC"; break; default: ... } if(isset($function)) { executeSth(); $function(); }
I also made a small live test bed here , if someone wants to test their PHP solutions before publishing them ( case 10 should executeSth() and executeA() , case 20 should executeSth() and executeB() , default should executeDefault() ).
In C ++, you can use a function pointer to achieve the same as above
I had a complete brain fart when I wrote this, fortunately idipous reminded me that we can do this with a simple function pointer.
// Declare function pointer int (*functionCall)() = NULL; // In switch statement, assign something to it functionCall = &execute; // After the switch statement, call it int result = (*functionCall)();
Note. I went out, so I did not check the syntax for them. The syntax I used is C syntax and may require some minor changes to work in C ++.
source share