Breaking out of the loops

March 24th, 2005. Tagged: PHP certification

The cert guide is maybe not 100% clear on the question of breaking out of a loop, but you can break and continue in all types of loops - for, while and foreach (the latter wasn't mentioned in the loops section of the book).

About the continue when in nested loops. Well, it is true that you can do
< ?php for ($i = 0; $i < 10; $i++){ for ($j = 0; $j < 10; $j++){ if ($i % 2) { continue 2; } } // this line will be executed 5 times // and will write 0 2 4 6 8 echo $i; } ?>
Or you can just continue or continue 1, rather than continue 2, like this
< ?php for ($i = 0; $i < 10; $i++){ for ($j = 0; $j < 10; $j++){ if ($i % 2) { continue; } } // this line will be executed 10 times // and will write 0 1 2 3 4 5 6 7 8 9 echo $i; } ?>

So yes, it is possible, but to me, these continue 2, continue 3 and so on can only cause confusion and make the code harder to follow. If I find myself in situation where I write continue 2, I would seriously think about restructuring this particular piece of logic.

Tell your friends about this post on Facebook and Twitter

Sorry, comments disabled and hidden due to excessive spam.

Meanwhile, hit me up on twitter @stoyanstefanov