Special loop keywords

There are two special keywords you can use with loops, and they are "break" and "continue". We already used break previously when we looked at case switching - it is used there to exit a switch/case block, and it has the same effect with loops. When used inside loops in order to manipulate the loop behaviour: break causes PHP to exit the loop and carry on immediately after it, and continue causes PHP to skip the rest of the current loop iteration and go onto the next.

For example:

<?php
    for ($i = 1; $i < 10; $i = $i + 1) {
        if ($i == 3) continue;
        if ($i == 7) break;
        print "Number $i\n";
    }
?>

That is a modified version of our original for loop script. This time the output is this:

Number 1
Number 2
Number 4
Number 5
Number 6

Note that number 3 is missed out entirely, and the script exits after number 6. The reason for this is because of the two if statements - if the current number is 3, "continue" is used to skip the rest of that iteration and go on to number 4. Also, if the number is 7, "break" is used to exit the loop altogether.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Loops within loops >>

Previous chapter: Infinite loops

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.