user3740970 user3740970 - 29 days ago 21
PHP Question

How to create a nested loop and display the result in 3 columns?

Im trying to creating a for loop and another for loop inside it and then display the results in 3 columns. It should look like this:

0(0) 0(1) 0(2)
1(0) 1(1) 1(2)
2(0) 2(1) 2(2)
3(0) 3(1) 3(2)


Right now I have this PHP script:

for ($x = 0; $x < 4; $x++) {
echo "$x";
for($y = 0; $y < 3; $y++){
echo "($y)<br/>";
}
}


Thanks in advance :)

Answer

The outer loop is for rows, the inner loop is for columns. So you should print <br/> in the outer loop. And since you want $x printed in each column, you need to print that in the inner loop.

for ($x = 0; $x < 4; $x++) {
    for($y = 0; $y < 3; $y++){
        echo "$x($y) ";
    }
    echo "<br/>";
}