user3479267
user3479267

Reputation: 232

Loop through a PHP Multidimensional Array

Im trying to create a 2D array with a specific number of rows and cols which I have stored as the variable $n ; so if $n was 5, I would have 5 rows and 5 cols, all with random numbers. I have created a for loop (as shown below) that generates the correct amount of rows but I cannot figure out how to do the same with the columns at the same time. The code I have at the moment is shown below.

<?php

    $n = 3;

    for($i=0; $i<=$n; $i++) {
        $value[$i][0] = rand(1,20);
        $value[$i][1] = rand(1,20);
        $value[$i][2] = rand(1,20);
        $value[$i][3] = rand(1,20);
    }   

    print "<table>";    
    for($j=0; $j<$n; $j++)  { // Runs the loop times $n
        print "<tr>";
        for($k=0; $k<$n; $k++)  { // Runs the loop times $n
            print "<td>" . $value[$j][$k] . "</td>";
        }   
        print   "</tr>";    
    }   
    print   "</table>";

?>

Any help would be appreciated in learning to create this loop of the array. Thanks in advance.

Upvotes: 0

Views: 32

Answers (2)

Rapha&#235;l Vig&#233;e
Rapha&#235;l Vig&#233;e

Reputation: 2045

Try this instead :

$n = 3;

for($i=0; $i<=$n; $i++) {
    $value[$i][0] = rand(1,20);
    $value[$i][1] = rand(1,20);
    $value[$i][2] = rand(1,20);
    $value[$i][3] = rand(1,20);
}   

print "<table>";    
foreach($value as $row){
    print "<tr>";
    foreach($row as $cell){
        print "<td>" . $cell . "</td>";
    }
    print "</tr>";
}
print "</table>";

And using a for loop :

print "<table>";
for($i=0; $i<=$n; $i++) { // rows
    print "<tr>";
    for($j=0; $j<=(count($value[$i])-1); $j++) { // columns
        echo "<td>".$value[$i][$j]."</td>";
    }
    print "</tr>";
}
print "</table>";

Upvotes: 1

Jeffwa
Jeffwa

Reputation: 1143

You need a second loop inside the first loop:

for($i=0; $i<=$n; $i++) { // rows
    for($j=0; $j<=$n; $j++) { // columns
        $value[$i][$j] = rand(1,20);
    }
}

Upvotes: 1

Related Questions