Hudzilla.org - the homepage of Paul Hudson PHP and PHP
Contents > Introducing PHP > How PHP is written Wish List | Report Bug | About Me ]

2.6.13     Loops within loops

NOTE: This is NOT the latest copy of this book; click here for the latest version.

You can stack loops up as you see fit simply by having one loop inside the body of another, like this:

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

The output of that script is:

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 closest loop. For example:

for ($i = 1; $i < 3; $i = $i + 1) {
    for (
$j = 1; $j < 4; $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 < 4; $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.

It is important to remember that "break" works both on loops and switch/case statements. For example:

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

The "break 2" line will break out of the switch/case block and also out of the $k loop, whereas the "break 3" line will break out of those two and also the $j loop. To break out of the loops entirely from within the switch/case statement, "break 4" is required.



<< 2.6.12 Special loop keywords   2.6.14 Mixed-mode processing >>
Table of Contents
Top-right shadow
 
Bottom-left shadow Bottom shadow