简体   繁体   中英

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.

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';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM