If the swicth statement does not have a break instruction, the theory that is executed is not understood even if the condition is not satisfied.
Case 1 in the left image is executed even though the condition is not met.
However, case 0 of the right image is not executed because the condition is not satisfied.
What is the difference between the two?
Is the rule that the block before the break is executed regardless of whether the condition is met?

I ’m sorry for the first question, but I ’d like to answer it.

  • Answer # 1

    The behavior specification (law) is

    If the condition corresponds tocase, the processing described in allcaseis executed until it hits Break

    For example

    $name = "banana";
    switch ($name) {
      case "banana":
      case "apple":
      case "Grape":
        echo "fruit";
      case "radish":
      case "carrot":
      case "Hakusai":
        echo "vegetables";
        echo "food";

    If you write it like

    If$nameis a banana or apple or grape, "fruit" is displayed

    For radish or carrot or Chinese cabbage, "vegetable" is displayed

    Other than that, "food" is displayed

    It feels like

    (Whether this description is desirable is another story.)

    PHP manual for behavior Switch
    Please check because it is explained in.


    It is important to understand how the switch statement is executed to avoid failure. The switch statement is executed line by line. (In fact, it is executed for each statement.) Initially, nothing is executed. When a case statement with an expression that evaluates to the same value as the switch expression is found, the instruction is executed by PHP for the first time. PHP continues execution until the end of the switch block or the first break statement. If you do not write a break statement at the end of a CASE statement, PHP continues to execute the next CASE statement. For example,


    Here, if $i is equal to 0, PHP will output all echo statements! If $i is 1, PHP will output the last two echo statements. Only if $i is equal to 2 does 'expected' behave and displays 'i equals 2'. For this reason (in some circumstances you may want to avoid adding a BREAK), it is important not to forget the break statement.

      In a

    switch statement, the condition is evaluated once and the result is compared with each case statement. In an elseif statement, the condition is evaluated again. If the processing to be used is more complicated than the simple comparison processing, or if heavy repeated processing is performed, the switch may be faster.