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: 2In 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: 1As 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: 1This 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 ...