The topic of
continue came up the other day and I thought it would make for a good blog post. You’re probably familiar with
break moreso than
continue because it is part of a
switch statement’s syntax. Both
continue can also be used inside of looping statements like
foreach. According to php.net
continue can also be used with
switch statements because it is also considered a looping structure.
When used inside of looping statements,
continue serve similar yet different purposes.
break is for ending the loop indefinitely while
continue is used to skip the rest of the current iteration and move on to the next iteration.
Print only even numbers
Find Bobby Fischer
You may have noticed that the
break were not really necessary in the examples above. If you did notice that, you would be correct! The truth is, you can usually write code without using
break just by writing a conditional statement (which you’d have to write anyway ;).
break can play an important role when looping through large datasets and want to ensure that it stops as soon as possible instead of looping through all of the data. At the same time, you can usually accomplish finding data in arrays by other less system intensive methods.
continue also accept a single, optional argument that tells it how many levels of loops to skip or break out of. The default is 1 to either skip the current iteration or current loop.