In this lesson, you will learn about PHP’s break and continue keywords, their usage, and examples to understand the topic better.
PHP’s break statement halts current operation while switching, iterating through the for-each and while loops. Break only interrupts the execution of the inner loop when used inside of it.
jump statement; break;
<?php echo "PHP ***doWhile loop*** Example"; echo "<br>"; echo " ------------do-while loop ------------------ "; echo "<br>"; echo "The table of 2 "; echo "<br>"; $var = 1; do { if ($var >= 6) { break; } $evennumber = 2 * $var; echo "2 * $var is $evennumber <br/>"; $var++; } while ($var <= 10) ?>
Output
PHP ***do-while loop*** Example ------------do-while loop ------------------ The table of 2 2 * 1 is 2 2 * 2 is 4 2 * 3 is 6 2 * 4 is 8 2 * 5 is 10
The above script will print half of the table because the break executes when $var
is equal to 6.
<?php echo "PHP ***Nested While loop with break statement*** Example"; echo "<br>"; echo " ------------Break Statement ------------------ "; echo "<br>"; $var = 1; while ($var <= 4) { echo 'Outer Loop ' . "$var" . " times <br/>"; $var2 = 1; while ($var2 <= 3) { if ($var2 >= 2) { break; } echo 'Nested Loop ' . "$var2" . " times <br/>"; $var2++; } $var++; echo "<br/> "; } ?>
Output
PHP ***Nested While loop with break statement*** Example ------------Break Statement ------------------ Outer Loop 1 times Nested Loop 1 times Outer Loop 2 times Nested Loop 1 times Outer Loop 3 times Nested Loop 1 times Outer Loop 4 times Nested Loop 1 times
The PHP break statement in the above script will only break the execution of the inner loop as the condition with the break statement is defined in the inner loop. It will only show output 1 time because the condition becomes true when var2 >= 2
Sometimes we need to skip the loop’s remaining statements that haven’t been executed to return to the beginning of the loop. This is made possible by using the continue keyword, and the control automatically moves to the beginning of the loop when the keyword is carried out repeatedly within a loop.
Example
<?php echo "PHP *** Continue Statement*** Example"; echo "<br>"; echo "<br>"; $var = 1; //Loop executes10 times, at even numbers continue statement will be executed and only'Odd numbers between 1 to 10 will be printed <br />'; while ($var <= 10) { if (($var % 2) == 0) { echo 'Continue executed when var = ' . $var . '<br />'; $var++; continue; } else { echo 'Odd number ' . $var . ' <br />'; $var++; } } ?>
Output
PHP *** Continue Statement*** Example Odd number 1 Continue executed when var = 2 Odd number 3 Continue executed when var = 4 Odd number 5 Continue executed when var = 6 Odd number 7 Continue executed when var = 8 Odd number 9 Continue executed when var = 10
This concludes the PHP break and continue lesson. In the next lesson, we will cover an essential topic in programming, functions!