0

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.

2 Answers 2

1

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Worked perfectly, thanks very much. I'll accept answer whenever it allows me.
1

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>";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.