Friday, 14 December 2012

Episode 10: Breaking out of a loop





Sometimes you want your script to break out of a loop. PHP provides two statements for this purpose:
break: Breaks completely out of a loop and continue with the script statements after the loop.

continue: Skips to the end of the loop where the condition is tested. If the condition tests positive, the script continues from the top of the loop.

The break and continue statements are usually used in conditional statements. In particular, break is used most often in switch statements.

The following statements show the difference between continue and Scripts break. This first chunk of code shows an example of the break statement:

$counter = 0;
while ( $counter < 5 )
{
$counter++;
If ( $counter == 3 )
{
echo “break\n”;
break;
}
echo “Last line in loop: counter=$counter\n”;
}
echo “First line after loop\n\n”;

The output of this statement is the following:

Last line in loop: counter=1
Last line in loop: counter=2
break
First line after loop

Notice that the first loop ends at the break statement. It stops looping and jumps immediately to the statement after the loop. That’s not true of the continue statement.

The following code gives you an example of the continue statement:
$counter = 0;
while ( $counter < 5 )
{
$counter++;
If ( $counter == 3 )
{
echo “continue\n”;
continue;
}
echo “Last line in loop: counter=$counter\n”;
}
echo “First line after loop\n”;

The output of this statement is the following:

Last line in loop: counter=1
Last line in loop: counter=2
continue
Last line in loop: counter=4
Last line in loop: counter=5
First line after loop

Unlike the break statement loop, this loop does not end at the continue statement. It just stops the third repeat of the loop and jumps back up to the top of the loop. It then finishes the loop, with the fourth and fifth repeats, before it goes to the statement after the loop.
One use for break statements is insurance against infinite loops. The following statements inside a loop can stop it at a reasonable point:
$test4infinity++;
if ($test4infinity > 100 )
{
break;
}
If you’re sure that your loop should never repeat more than 100 times, use these statements to stop the loop if it becomes endless. Use whatever number seems reasonable for the loop you’re building.


Written by “Shojib”.

No comments:

Post a Comment