Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Special Loop Keywords

PHP gives you the break and continue keywords to control loop operation. We already used break previously when we looked at case switching—it was used there to exit a switch/case block, and it has the same effect with loops. When used inside loops to manipulate the loop behavior, 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 on to the next.

Tip

Perl users should note that break and continue are equivalent to Perl's last and next statements.

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 looks like this:

    Number 1
    Number 2
    Number 4
    Number 5
    Number 6

Note that Number 3 is missing, and the script exits after Number 6. When 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.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page