PHP Switch Case

Will the default value of the switch statement be evaluated if there is a corresponding case in front of it?

Example:

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

so for x = 50 you will see fooand bar, or fooand barand nope?

+5
source share
4 answers

Yes, if there is no "break", then all actions following the first will be performed case. The control thread will β€œfail” in all subsequent ones caseand perform all actions under each subsequent caseone until an operator is met break;or until the end of the instruction is reached switch.

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

, switch , switch, , case.

, "foo", $x 0. (, $x 0, , , "foo bar nope". )

, case, return 0 ( false) 1 ( ). (0 1), switch $x.

+4

switch, ?

case , break. default.

, , ( ):

$x = 10;

switch (true) {
  case ($x > 5):
      print "foo";

  case ($x%2 == 0):
      print "bar";

  default:
      print "nope";
}

foobarnope. , : yep: -)

+5

. , break , ( )

+2

, .

:

switch IF . ( ) , . , switch.

,

case ($x > 5):

case true:

case false:

$x, ($x > 5) - , VALUE. , , case s.

switch($x) {
    case ($x > 5): // $x == ($x > 5)
        echo "foo";
        break;
    case ($x <= 5): // $x == ($x <= 5)
        echo "bar"
        break;
    default:
        echo "default";
        break;
}

if ($x == ($x > 5)) {
    echo "foo";
} elseif ($x == ($x < 5)) {
    echo "bar";
} else {
    echo "five";
}

( $x == 50)

if ($x == true) {
    echo "foo";
} elseif ($x == false) {
    echo "bar";
} else {
    echo "five";
}

if (true) { // $x == true is the same as saying "$x is truthy"
    echo "foo";
} elseif (false) {
    echo "bar";
} else {
    echo "five";
}

IF, switch, ( ):

switch ($x) {
    case 50:
        echo "foo ";
    case 30:
        echo "bar ";
    default:
        echo "foo-bar";
}

$x == 50,

foo bar foo-bar

- , break.

break , .

switch ($x) {
    case 50:
        echo "foo ";
        break;
    case 30:
        echo "bar ";
        break;
    default:
        echo "foo-bar";
        break;
}

:

foo 
+1

All Articles