15

I have the following loop and I want to continue the while loop when the check inside the inner loop has meet the condition. I found a solution here (which is I applied in the following example), but it is for c#.

    $continue = false;
    while($something) {

       foreach($array as $value) {
        if($ok) {
          $continue = true;
           break;
           // continue the while loop
        }

           foreach($value as $val) {
              if($ok) {
              $continue = true;
              break 2;
              // continue the while loop
              }
           }
       }

      if($continue == true) {
          continue;
      }
    }

Is PHP has its own built it way to continue the main loop when the inner loops have been break-ed out?

Community
  • 1
  • 1
Ari
  • 4,643
  • 5
  • 36
  • 52

2 Answers2

32

After reading the comment to this question (which was deleted by its author) and did a little research, I found that there is also parameter for continue just like break. We can add number to the continue like so:

while($something) {

   foreach($array as $value) {
    if($ok) {
       continue 2;
       // continue the while loop
    }

       foreach($value as $val) {
          if($ok) {
          continue 3;
          // continue the while loop
          }
       }
   }
}
Ari
  • 4,643
  • 5
  • 36
  • 52
1

I think as you are not running the continue until you have processed the complete inner foreach it is irrelevant. You need to execute the continue in situ and not wait until the end of the loop.

Change the code to this

while($something) {

    foreach($array as $value) {
        if($ok) {
            continue;    // start next foreach($array as $value)
        }

        foreach($value as $val) {
            if($ok) {
               break 2;    // terminate this loop and start next foreach($array as $value)
            }
        }
    }

}

RE: Your comment

while($something) {

    if($somevalue) {
        // stop this iteration
        // and start again at iteration + 1
        continue;    
    }


}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
  • The real case is just to find a value and go for the next iteration of the `while` loop. So I made it like that. The comment for `continue` key in your `foreach` loop seem for me telling that it is continuing the `while` loop. Is that it? – Ari Sep 09 '15 at 17:54
  • No, `continue` just starts the _loop that it is used in_ from the next iteration – RiggsFolly Sep 09 '15 at 17:55
  • See additional info re your comment. I hope this is what you mean! – RiggsFolly Sep 09 '15 at 17:58