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.
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.
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.
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.
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.
switch ($i) {     case A:     case B:     case C:         $letter = 'first';         break;     case D:         $letter = 'second';         break;     default:         $letter = 'third'; } 
                        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