Example:
Break Statement
<html>
<head>
<title>Break Statement</title>
</head>
<body>

<?php
$i = 0;

while ( $i < 6 )
{
if( $i == 3) break;
$i++;
}
echo("Loop stopped at $i by break statement");
?>

</body>
</html>

Example:
Result:
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

Using the break Statement
<html>
<head><title>Using the break Statement</title></head>
<body>
<div>
<?php
$counter = -4;
for ( ; $counter <= 10; $counter++ ) {
if ( $counter == 0 ) {
break;
}
$temp = 4000/$counter;
print "4000 divided by $counter is.. $temp<br />";
}
?>
</div>
</body>
</html>

Example:

Result:

Non-prime number encountered: 1
Non-prime number encountered: 49
Non-prime number encountered: 33

break within a for loop
<?php
$primes = array(2,3,5,7,11,13);
for($count = 1; $count++; $count < 1000) {
$randomNumber = rand(1,50);
if (in_array($randomNumber,$primes)) {
break;
} else {
echo "<p>Non-prime number encountered: $randomNumber</p>";
}
}
?>

Example:

Using break to avoid division by zero
<?php

$counter = -3;

for (; $counter < 10; $counter++){
if ($counter == 0){
echo "Stopping to avoid division by zero.";
break;
}

echo "100/$counter<br />";
}

?>

0 comments:

Post a Comment

 
Top
Blogger Template