Break
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 below show how to use the Break statement:
echo "
Example of using the Break statement:
";for ($i=0; $i<=10; $i++) {
if ($i==3){break;}
echo "The number is ".$i;
echo "
";
}
echo "
One more example of using the Break statement:
";
$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."
";
echo "The second number is ".$j."
";
?>
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:
echo "
Example of using the Continue statement:
";
for ($i=0; $i<=10; $i++) {
if (i==3){continue;}
echo "The number is ".$i;
echo "
";
}
?>