Break
Loops are very useful to help sift through information for what you need. However once you find your data you probably would like your loop to stop. For that you would have to use the BREAK statement.
In this case the BREAK statement was used to not generate a division by zero warning. Watch as the code is stopped right before division by zero occurs.
<?php
$count = -10;
for (;$count <= 10; $count++) {
if ($count == 0) {
break;
} else {
$result = 200/$count;
echo "200 divided by $count is $result<br />";
}
}
?>
Results:
200 divided by -10 is -20
200 divided by -9 is -22.222222222222
200 divided by -8 is -25
200 divided by -7 is -28.571428571429
200 divided by -6 is -33.333333333333
200 divided by -5 is -40
200 divided by -4 is -50
200 divided by -3 is -66.666666666667
200 divided by -2 is -100
200 divided by -1 is -200
Continue
The continue statement ends the execution of the current code lap but doesn’t stop the whole loop from continuing.
The following code, similar to the break, will stop the code from dividing by zero but continue afterwards.
<?php
$count = -10;
for (;$count <= 10; $count++) {
if ($count == 0) {
continue;
} else {
$result = 200/$count;
echo "200 divided by $count is $result<br />";
}
}
?>
Results:
200 divided by -10 is -20
200 divided by -9 is -22.222222222222
200 divided by -8 is -25
200 divided by -7 is -28.571428571429
200 divided by -6 is -33.333333333333
200 divided by -5 is -40
200 divided by -4 is -50
200 divided by -3 is -66.666666666667
200 divided by -2 is -100
200 divided by -1 is -200
200 divided by 1 is 200
200 divided by 2 is 100
200 divided by 3 is 66.666666666667
200 divided by 4 is 50
200 divided by 5 is 40
200 divided by 6 is 33.333333333333
200 divided by 7 is 28.571428571429
200 divided by 8 is 25
200 divided by 9 is 22.222222222222
200 divided by 10 is 20


Sat, Jul 26, 2008
Code, PHP