0

It is possible to go to default case from within some other case like this?

$a = 0;
$b = 4;
switch ($a) {
    case 0:
        if ($b == 5) {
            echo "case 0";
            break;
        }
        else
            //go to default
    case 1:
        echo "case 1";
        break;
    default:
        echo "default";
}

I tried to remove the else and was expecting that it would continue evaluating all following cases until default but it gets into case 1 then. Why is it so and how can I get to the default one?

yaugenka
  • 2,602
  • 2
  • 22
  • 41
  • Personal suggestion: ditch the `switch` / `case` when it's not straightforward enough. Simply use an `if` / `else` instead: https://3v4l.org/OEkD6 – Jeto Dec 29 '19 at 15:56

3 Answers3

3

Yes you can if you reorder the case statements:

switch ($a) {
    case 1:
        echo "case 1";
        break;
    case 0:
        if ($b == 5) {
            echo "case 0";
            break;
        }
    default:
        echo "default";
}

Why is it so: it is defined, if you de not have a break statement the next case will be executed. If there is no more case, the default will be executed if one is defined

Jens
  • 67,715
  • 15
  • 98
  • 113
  • Is it not supposed to evaluate each case before executing it? – yaugenka Dec 29 '19 at 16:00
  • @yaugenka No it shouldn't – Jens Dec 29 '19 at 16:03
  • 3
    This answer is right - and it's what the original poster asked for - but it's generally accepted that it's not a good idea to use the 'fall through' feature of switch (that is, where you don't `break`, and just carry on into the next case) like this as it's highly unusual, and therefore very confusing to anyone who has read your code in the future. – Ben XO Dec 29 '19 at 16:08
  • Think https://stackoverflow.com/questions/188461/switch-statement-fallthrough-should-it-be-allowed talks about this a bit more. – Nigel Ren Dec 29 '19 at 16:22
1

You could re-order the case statements to allow a fall through to the next option, but if there are several times you wish to do this it can become impossible or just very fragile. The alternative is to just more the common code into a function...

function defaultCase()  {
     echo "default";
}

switch ($a) {
    case 0:
        if ($b == 5) {
            echo "case 0";
        }
        else {
            defaultCase();
        }
        break;
    case 1:
        echo "case 1";
        break;
    default:
       defaultCase();
}
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
0

I would suggest using a simple if / else as I mentioned in the comments.

However, here's another way you could do it using a switch statement, if that helps:

switch ([$a, $b]) {
  case [0, 5]:
    echo 'case 0';
    break;
  case [1, $b]:
    echo 'case 1';
    break;
  default:
    echo 'default';
}
Jeto
  • 14,596
  • 2
  • 32
  • 46