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

Loops Within Loops

You can nest loops as you see fit, like this:

    for ($i = 1; $i < 3; $i = $i + 1) {
            for ($j = 1; $j < 3; $j = $j + 1) {
                    for ($k = 1; $k < 3; $k = $k + 1) {
                            print "I: $i, J: $j, K: $k\n";
                    }
            }
    }

Here's the output:

    I: 1, J: 1, K: 1
    I: 1, J: 1, K: 2
    I: 1, J: 2, K: 1
    I: 1, J: 2, K: 2
    I: 2, J: 1, K: 1
    I: 2, J: 1, K: 2
    I: 2, J: 2, K: 1
    I: 2, J: 2, K: 2

In this situation, using break is a little more complicated, as it only exits the containing loop. For example:

    for ($i = 1; $i < 3; $i = $i + 1) {
            for ($j = 1; $j < 3; $j = $j + 1) {
                    for ($k = 1; $k < 3; $k = $k + 1) {
                            print "I: $i, J: $j, K: $k\n";
                            break;
                    }
            }
    }

This time the script will print out the following:

    I: 1, J: 1, K: 1
    I: 1, J: 2, K: 1
    I: 2, J: 1, K: 1
    I: 2, J: 2, K: 1

As you can see, the $k loop only loops once because of the break call. However, the other loops execute several times. You can exercise even more control by specifying a number after break, such as break 2, to break out of two loops or switch/case statements. For example:

    for ($i = 1; $i < 3; $i = $i + 1) {
            for ($j = 1; $j < 3; $j = $j + 1) {
                    for ($k = 1; $k < 3; $k = $k + 1) {
                            print "I: $i, J: $j, K: $k\n";
                            break 2;
                    }
            }
    }

That outputs the following:

    I: 1, J: 1, K: 1
    I: 2, J: 1, K: 1

This time the loop only executes twice, because the $k loop calls break 2, which breaks out of the $k loop and out of the $j loop, so only the $i loop will go around again. This could even be break 3, meaning break out of all three loops and continue normally.

The break command ...

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