PHP

PHP Break and Continue

PHP Break and Continue
Written by ProgrammingPot

While not used very often in PHP Break and Continue deserve much more credit. Continue and break provide extra control over your loops by manipulating the flow of the iterations. Continue is the nicer one of the two as it prevents the current iteration, or flow through one pass of the loop, and just tells PHP to go to the next round of the loop.

Break provides more aggressive control by completing skipping out of the loop and onto the code following the loop. If you have ever played the card game UNO, continue is basically the skip card, and break is someone slamming their cards down screaming I am the winner and leaves the room. Let’s go through some examples to see how to use them.

PHP Break and Continue


PHP Break

break ends execution of the current for, foreach, while, do-while or switch structure.

break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. The default value is 1, only the immediate enclosing structure is broken out of.

A break statement that is in the outer part of aprogram (e.g. not in  a control loop) will end the script. This caught me out when I mistakenly had a break in an if statement

Example

<?php
echo "hello";
if (true) break;
echo " world";
?>

Output

will only show "hello"

PHP Continue

continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.

continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of. The default value is 1, thus skipping to the end of the current loop.

Example

<?php
for ($i = 0; $i < 5; ++$i) {
    if ($i == 2)
        continue
    print "$i\n";
}
?>

One can expect the result to be:

0
1
3
4

but, in PHP versions below 5.4.0, this script will output:

2

because the entire continue print “$i\n”; is evaluated as a single expression, and so print is called only when $i == 2 is true. (The return value of print is passed to continue as the numeric argument.)

 

Note:

As of PHP 5.4.0, the above example will raise an E_COMPILE_ERROR error.

 

Leave a Comment