Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch, same value for multiple case

switch ($i) {     case A:         $letter = 'first';         break;     case B:         $letter = 'first';         break;     case C:         $letter = 'first';         break;     case D:         $letter = 'second';         break;     default:         $letter = 'third'; } 

Is there any way to shorten first three cases?

They have the same values inside.

like image 830
James Avatar asked Sep 02 '10 16:09

James


People also ask

Can switch case have same value?

Control passes to the case statement whose constant-expression value matches the value of expression . The switch statement can include any number of case instances. However, no two constant-expression values within the same switch statement can have the same value.

Can switch case have multiple conditions?

A switch statement includes literal value or is expression based. A switch statement includes multiple cases that include code blocks to execute. A break keyword is used to stop the execution of case block. A switch case can be combined to execute same code block for multiple cases.

Can we use multiple 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.


2 Answers

switch ($i) {     case A:     case B:     case C:         $letter = 'first';         break;     case D:         $letter = 'second';         break;     default:         $letter = 'third'; } 

Yep there is. If there's no break after a case, the code below the next case is executed too.

like image 131
svens Avatar answered Sep 19 '22 13:09

svens


switch ($i) {     case A:     case B:     case C:         $letter = 'first';         break;     case D:         $letter = 'second';         break;     default:         $letter = 'third'; } 
like image 31
Otar Avatar answered Sep 20 '22 13:09

Otar