62

I am trying to skip to the next iteration of the loop if certain conditions are not met. The problem is that the loop is continuing regardless.

Where have I gone wrong?

Updated Code sample in response to first comment.

    foreach ($this->routes as $route => $path) {
        $continue = 0;

        ...

        // Continue if route and segment count do not match.
        if (count($route_segments) != $count) {
            $continue = 12;
            continue;
        }

        // Continue if no segment match is found.
        for($i=0; $i < $count; $i++) {
            if ($route_segments[$i] != $segments[$i] && ! preg_match('/^\x24[0-9]+$/', $route_segments[$i])) {
                $continue = 34;
                continue;
            }
        }

        echo $continue; die(); // Prints out 34
cdhowie
  • 158,093
  • 24
  • 286
  • 300
ComputerUser
  • 4,828
  • 15
  • 58
  • 71
  • 1
    You are overwriting `$continue`. It is entirely possible to enter that it gets set to 1, then 2 in your loop iterations. – Jason McCreary Nov 24 '10 at 18:11
  • 1
    Set `$continue = 0;` right after the `foreach`... I'll bet you won't get `1` anymore. A for 2, you'd need to tell it to continue up 2 levels, so `continue 2;`, otherwise it'll just go to the next iteration of the `for` loop... – ircmaxell Nov 24 '10 at 18:14

4 Answers4

122

If you are trying to have your second continue apply to the foreach loop, you will have to change it from

continue;

to

continue 2;

This will instruct PHP to apply the continue statement to the second nested loop, which is the foreach loop. Otherwise, it will only apply to the for loop.

cdhowie
  • 158,093
  • 24
  • 286
  • 300
23

The second continue is in another loop. This one will only "restart" the inner loop. If you want to restart the outer loop, you need to give continue a hint how much loops it should go up

continue 2;

See Manual

KingCrunch
  • 128,817
  • 21
  • 151
  • 173
11

You are calling continue in a for loop, so continue will be done for the for loop, not the foreach one. Use:

continue 2;
netcoder
  • 66,435
  • 19
  • 125
  • 142
1

The continue within the for loop will skip within the for loop, not the foreach loop.

BeemerGuy
  • 8,139
  • 2
  • 35
  • 46