I really like the structure of the switch statement compared to using multiple if else. However some times I want to use the switch statement and have the same value in multiple cases. Can this be done somehow?
switch($fruit) {
case 'apple':
case 'orange':
// do something for both apples and oranges
break;
case: 'apple':
// do something for only apples
break;
case: 'orange':
// do something for only oranges
break;
}
I hope my example show what I intend to do...
No, it cannot. The first case that matches and everything following it until the first break statement or the end of the switch statement will be executed. If you break, you break out of the switch statement and cannot re-enter it. The best you could do is:
switch ($fruit) {
case 'apple':
case 'orange':
...
switch ($fruit) {
case 'apple':
...
case 'orange':
...
}
}
But really, don't. If you need some special action for those two before the individual switch, do an if (in_array($fruit, ['apple', 'orange'])) ... before the switch. Or rethink your entire program logic and structure to begin with.
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