Break and Continue

Do you know that operators 'break' and 'continue' have one optional int parameter?
I didn't.

The trick is: when you have multiple nested cycles, you may want to break or to continue not only the current loop iteration, but also parent loop iteration. This optional parameter gives a clue of how many loop layers to break (or to continue).
Looks like following:

for ($i=0; $i<10; $i++)
  for ($j=2; $j<20; $j+=2)
  {
    if ($i == $j) {
      echo $i . '=' . $j . "\n";
      continue 2;
    }
    echo $i . '!=' . $j . "\n"';
  }

Something like that. I mean - if you still can't understand the sense of parameter - try to execute it and change 'continue 2' to 'continue';
Yes, it's senseless code.

Leave a Reply