The break, goto and continue statement

      No Comments on The break, goto and continue statement

The break, goto and continue statement are used to shift the control of loop to particular point.

The break statement

Encountering the break statement will end the execution of for, while,do….while,for each or switch block loop.
For example, the following for loop will terminate if a prime number is pseudo-randomly happened upon:

<?php
$primes = array(2,3,5,7,11,13,17,19,23,29,31,37,41,43,47);
for($count = 1; $count++; $count < 1000)
{ $randomNumber = rand(1,50);
if (in_array($randomNumber,$primes))
 { 
  break;
}
else { }
}
?>

Output follows:

Non-prime number found: 48
Non-prime number found: 42
Prime number found: 17

The break, goto and continue statement

Goto statement

Goto statement was added in PHP 5.3 to extent support to the break statements. This is used to suddenly jump to a specific location outside the loop or a conditional statement.

For example:

<?php
for ($count = 0; $count < 10; $count++)
{
$randomNumber = rand(1,50);
if ($randomNumber < 10) 
goto less;
else 
echo "Number greater than 10: $randomNumber<br />";
}
less:
echo "Number less than 10: $randomNumber<br />";
?>

It produces the following

Number greater than 10: 22
Number greater than 10: 21

The break, goto and continue statement

Continue statement

The continue statement causes the execution of the current loop iteration to end and commence at the beginning of the loop

For example, execution of the following while body will recommence if $usernames[$x] is found to have the value missing:

<?php
$usernames = array("Grace","Doris","Gary","Nate","missing","Tom");
for ($x=0; $x < count($usernames); $x++)
{
if ($usernames[$x] == "missing") 
continue;
printf("Staff member: %s <br />", 
$usernames[$x]);
} ?>

This results in the following output:

Staff member: Grace Staff member: Doris
Staff member: Gary Staff member: Nate Staff member: Tom

The break, goto and continue statement

Leave a Reply

Your email address will not be published. Required fields are marked *