4

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 ?

d.raev
  • 9,216
  • 8
  • 58
  • 79

1 Answers1

4

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.

mishu
  • 5,347
  • 1
  • 21
  • 39
  • 1
    I would like to add that if you don't have any code in the outer loop after the inner loop, `continue 2` would be more readable because it communicates your intention better. `break` conveys the message that you want to stop or break out of something, while `continue n` conveys the message that you want to *skip to the next iteration*, which is the intention here. – Adrian Wiik Sep 22 '21 at 09:32