How to use the Break and continue statement ?
By Balu Prasad
Break and continue statement.....
Teacher SiliconIndia replied to Balu Prasad Wednesday, March 17, 2010
Hi Balu,
Sometimes you may want to let the loops start without any condition, and allow the statements inside the brackets to decide when to exit the loop. There are two special statements that can be used inside loops: Break and Continue.
The Break statement terminates the current While or For loop and continues executing the code that follows after the loop (if any). Optionally, you can put a number after the Break keyword indicating how many levels of loop structures to break out of. In this way, a statement buried deep in nested loops can break out of the outermost loop.
Examples of Break statement:
<?php
for ($i=0; $i<=10; $i++) {
if ($i==3){break;}
echo "The number is ".$i;
echo "<br />";
}
echo "<p><b>One more example of using the Break statement:</b><p>";
$i = 0;
$j = 0;
while ($i < 10) {
while ($j < 10) {
if ($j == 5) {break 2;} // breaks out of two while loops
$j++;
}
$i++;
}
echo "The first number is ".$i."<br />";
echo "The second number is ".$j."<br />";
?>
The Continue statement terminates execution of the block of statements in a While or For loop and continues execution of the loop with the next iteration:
Example of Continue statement:
<?php
for ($i=0; $i<=10; $i++) {
if (i==3){continue;}
echo "The number is ".$i;
echo "<br />";
}
?>