d.raev
d.raev

Reputation: 9556

difference between continue 2 and break in nested loops

I was refactoring some old code and stumbled on a continue 2 that can be easily replaced with a break.

for($rows as $i){
      for($columns as $j){
           if( Helper::unicornExists($i, $j) ){
                 //continue 2;  
                 break;
           }
      }
}

If we say that continue 2 makes the code more complicated and hard to read , is there any good reason to use it (in 2 level) nested loops ?

Upvotes: 4

Views: 2567

Answers (1)

mishu
mishu

Reputation: 5397

In this particular example it seems that it's the same thing and it is up to you to decide how you prefer it. One reason I can see to keep continue 2 would be if in a future development of your project you would add something after the inner for

for($rows as $i){
      for($columns as $j){
           if( Helper::unicornExists($i, $j) ){
                 //continue 2;  
                 break;
           }
      }
      echo 'done with ', $i, PHP_EOL;
}

You need to think what you expect if the unicorn does exist. Do you want to skip just the inner loop, and that's what break would do, or you want to skip the outer one also, and that's what continue 2 would do.

Upvotes: 4

Related Questions