Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch multiple case statement

Can someone suggest me how can I replace the below code?

How do I rewrite the code in order to avoid the repetition of the block case 3:{code block A; break;}?

switch(i) {   case 1:  {code block A; break;}    case 2:  {code block b; break;}    case 3:  {code block A; break;}    default: {code block default; break;} } 

How can I have combined code for case 1 and case 3?

like image 307
Unkown_Better Avatar asked Feb 27 '14 16:02

Unkown_Better


People also ask

How many cases a switch statement have?

Microsoft C doesn't limit the number of case values in a switch statement. The number is limited only by the available memory. ANSI C requires at least 257 case labels be allowed in a switch statement.

Can we write multiple statements in switch case in Java?

There can be one or 'N' number of cases in a switch statement. The case values should be unique and can't be duplicated. If there is a duplicate value, then it is a compilation error. The data type of the values for a case must be the same as the data type of the variable in the switch test expression.


1 Answers

This format is shown in the PHP docs:

switch (i) {     case 1:     case 3:         code block A;         break;     case 2:         code block B;         break;     default:         code block default;         break; } 

EDIT 04/19/2021:

With the release of PHP8 and the new match function, it is often a better solution to use match instead of switch.

For the example above, the equivalent with match would be :

$matchResult = match($i) {     1, 3    => // code block A     2       => // code block B     default => // code block default } 

The match statement is shorter, doesn't require breaks and returns a value so you don't have to assign a value multiple times.

Moreover, match will act like it was doing a === instead of a ==. This will probably be subject to discussion but it is what it is.

like image 167
B F Avatar answered Sep 23 '22 05:09

B F