[Solved] How eliminate duplicate cases from a switch statement in PHP


If you have switch cases that are the same, you can combine them by omitting the return and break lines of the earlier cases.

In the following, 3, 4, 5 and 6 all take the return value of case 7 (true):

switch($role) {
    case 3:
    case 4:
    case 5:
    case 6:
    case 7:
        return true;
        break;
    default:
        return false;
        break;
}

Although having said that, considering everything seems to return the same way apart from your default, you might be better off making use of a simple if condition. You can even specify that the roles should be between 3 and 7:

if ($role >= 3 && $role <= 7) {
    return true;
}
else {
    return false;
}

Hope this helps! 🙂

1

solved How eliminate duplicate cases from a switch statement in PHP