Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php foreach continue

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 
like image 688
JasonS Avatar asked Nov 24 '10 18:11

JasonS


People also ask

Can I use continue in foreach PHP?

Introduction. The continue statement is one of the looping control keywords in PHP. When program flow comes across continue inside a loop, rest of the statements in current iteration of loop are skipped and next iteration of loop starts. It can appear inside while, do while, for as well as foreach loop.

What is continue in foreach?

In C#, the continue statement is used to skip over the execution part of the loop(do, while, for, or foreach) on a certain condition, after that, it transfers the control to the beginning of the loop. Basically, it skips its given statements and continues with the next iteration of the loop.

How does continue work in PHP?

PHP Continue The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

What is the difference between break and continue in PHP?

The break statement terminates the whole iteration of a loop whereas continue skips the current iteration. The break statement terminates the whole loop early whereas the continue brings the next iteration early.


2 Answers

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.

like image 159
cdhowie Avatar answered Sep 19 '22 13:09

cdhowie


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

like image 29
KingCrunch Avatar answered Sep 18 '22 13:09

KingCrunch