Continue 2 and break in switch statement

I am new to PHP and see the code below on the internet. He has continue 2

and break

together in instructions switch/case

. What does it mean?

foreach ( $elements as &$element ) {

    switch ($element['type']) {
        case a :
            if (condition1)
                continue 2; 
            break;

        case b :
            if (condition2)
                continue 2;
            break;
    }

    // remaining code here, inside loop but outside switch statement
}

      

+16


source to share


4 answers


continue 2

skips directly to the next iteration of the structure, which is two levels back, which is foreach

. break

(equivalent break 1

) just terminates the statement switch

.

Behavior in the code you showed:

Loop over $elements

. If it $element

is of type "a" and is condition1

satisfied, or if it is of type b and is condition2

satisfied, go to the next one $element

. Otherwise, take some action before moving on to the next $element

.


From PHP.net : Continued :



continue takes an optional numeric argument that tells you how many levels of closed loops to skip to the end. The default is 1, which allows you to go to the end of the current loop.

From PHP.net:switch

PHP continues to execute statements until the end of a switch block, or until it first sees a break statement.

If you have a switch inside the loop and want to move to the next iteration of the outer loop, use continue 2.

+21


source


IMHO, the difference is that you have the code after the switch and before the end of the loop.



    foreach ( $elements as &$element ) {
        switch ($element['type']) {
            case a :
                if (condition1)
                    continue 2; 
                break;

            case b :
                if (condition2)
                    continue 2;
                break;
        }
        // The code here will be reached if break but not if continue 2
    }

      

+3


source


continue takes an optional numeric argument that tells it how many levels of closed loops it should skip to the end. The default is 1, thus skipping to the end of the current loop.

Source: http://php.net/manual/en/control-structures.continue.php

+2


source


continue and break are the same as they stop happening.

if you continue, it will stop something after the braces, but it will not stop the cycle. The switch statement just walks out of this statement and moves on to the next statement.

In case of rupture, it will stop the whole cycle from continuing, end the cycle.

+1


source







All Articles