17

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?

0

2 Answers 2

36

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
          }
       }
   }
}
Sign up to request clarification or add additional context in comments.

Comments

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;    
    }


}

3 Comments

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?
No, continue just starts the loop that it is used in from the next iteration
See additional info re your comment. I hope this is what you mean!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.