Search code examples
phpswitch-statementdefault

PHP switch case default


Will the default of a switch statement get evaluated if there's a matching case before it?

ex:

switch ($x) {
  case ($x > 5): print "foo";
  case ($x%2 == 0): print "bar";
  default: print "nope";
}

so for x = 50, you'd see foo and bar, or foo and bar and nope?


Solution

  • Yes, if there is no "break", then all actions following the first case matched will be executed. The control flow will "falls through" all subsequent case, and execute all of the actions under each subsequent case, until a break; statement is encountered, or until the end of the switch statement is reached.

    In your example, if $x has a value of 50, you would actually see "nope".

    Note that switch is actually performing a simple equality test, between the expression following the switch keyword, and each expression following the case keyword.

    Your example is unusual, in that it will only display "foo" when $x has a value of 0. (Actually, when $x has a value of 0, what you would see would be "foo bar nope".)

    The expression following the case keyword is evaluated, which in your case, example return a 0 (if the conditional test is false) or a 1 (if the conditional test is true). And it's that value (0 or 1) that switch will compare to $x.