Using the BREAK Statement

Chapter 6 #122 - Martha's CIS 52

ASSIGNMENT/EXPLANATION

The problem for code scripts is often that if the user creates the input for the test expression, it may not be of the right type needed. The following example creates a test for situations where the divisor is zero ( which would create an "undefined' result). Here, the break statement ends the code execution entirely, if the $counter is zero.

NOTICE: The $counter variable was initialized OUTSIDE of the for statement's parentheses. Also, any of the 3 expressions of a for statement may be omitted, but the semi-colon must be retained as a separation "placeholder".

Exercise

4000 divided by -4 is...-1000
4000 divided by -3 is...-1333.3333333333
4000 divided by -2 is...-2000
4000 divided by -1 is...-4000

CODE

<?php 
$counter = -4;
for (; $counter <= 10; $counter++) {
if ($counter == 0 ) {
break;
} else {
$temp = 4000/$counter;
echo "4000 divided by ".$counter." is...".$temp."<br />"; } }
?>