php foreach continue

PhpForeachContinue

Php Problem Overview


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

Php Solutions


Solution 1 - Php

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.

Solution 2 - Php

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

Solution 3 - Php

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

continue 2;

Solution 4 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJasonSView Question on Stackoverflow
Solution 1 - PhpcdhowieView Answer on Stackoverflow
Solution 2 - PhpKingCrunchView Answer on Stackoverflow
Solution 3 - PhpnetcoderView Answer on Stackoverflow
Solution 4 - PhpBeemerGuyView Answer on Stackoverflow