PHP break and continue
While not used very often in PHP, continue and break deserve much more credit. Continue and break provide extra control over your loops by manipulating the flow of the iterations. Continue is the nicer one of the two as it prevents the current iteration, or flow through one pass of the loop, and just tells PHP to go to the next round of the loop. Break provides more aggressive control by completing skipping out of the loop and onto the code following the loop. If you have ever played the card game UNO, continue is basically the skip card, and break is someone slamming their cards down screaming I am the winner and leaves the room. Let’s go through some examples to see how to use them.
$i = 0; for ($i = 0;$i <= 5;$i++) { if ($i==2) { break; } echo $i; echo " "; }
$i = 0; for ($i = 0;$i <= 5;$i++) { if ($i==2) { continue; } echo $i; echo " "; }
It seems pretty obvious that continue is different than break. Notice how the only result not printed is 2. The continue basically says let’s skip out of this particular instance of the loop and move onto the next one. When we are running through the instance where $i becomes equal to 2, we meet the conditional statement if( $i == 2) where it is true. Then, we execute the continue, which stops us from executing the following statements in the loop. We then run through the next iteration of the loop where $i equals 3. Since we don’t meet the conditional statement this time, we write the following statements and will never enter into conditional if($i == 2).
Leave A Comment