oktay oktay - 3 years ago 87
HTML Question

How to create random table grid with PHP?

I am new at PHP. I need randomized numbers from a pool to be seen in table.
I created with for loops but couldn't fill with all random numbers.
Right now unfortunately all cells show same number.

<?php
$size = 3;
$no = array(0,1,2,3,4,5,6,7,8,9,2,4,6,8);
?>
<table>
<?php
$number[] = $no[array_rand($no)];
for ($i=0; $i < $size; $i++){
foreach ($number as $cell)
{ ?><tr><?php
for ($b=0; $b < $size ;$b++){
foreach ($number as $cell){
echo '<td>'.$cell.'</td>';
}
}
}
?></tr><?php
}
?>
</table>

Answer Source

One way is to just pick a random key thru array_rand when its time to print a single cell, so just put that in there:

<?php $size = 3; $no = array(0,1,2,3,4,5,6,7,8,9,2,4,6,8); ?>
<table border="1">
<?php for ($i = 0; $i < $size; $i++){ ?>
    <tr>
    <?php for ($b = 0; $b < $size ;$b++) { ?>
        <td><?php echo $no[array_rand($no)]; ?></td>
    <?php } ?>
    </tr>
<?php } ?>
</table>

Sample Output

Or another way is to pick N number of keys when printing the inner loop:

<?php 
$size = 3; 
$no = array(0,1,2,3,4,5,6,7,8,9,2,4,6,8);
?>
<table>
<?php for($i = 0; $i < $size; $i++) { ?>
    <tr>
    <?php foreach(array_rand($no, $size) as $keys) { ?>
        <td><?php echo $no[$keys]; ?></td>
    <?php } ?>
    </tr>
<?php } ?>
</table>

Sample Output

Another weird way: (pre loaded random keys :p)

<?php 
$size = 3; 
$no = array(0,1,2,3,4,5,6,7,8,9,2,4,6,8);
$rands = array_map(function() use ($size, $no){
    return array_rand($no, $size);
}, array_fill(0, $size, array()));

?>
<table border="1">
<?php foreach($rands as $row){ ?>
    <tr><?php foreach($row as $c) { ?>
        <td><?php echo $no[$c]; ?></td>
    <?php } ?></tr>
<?php } ?>
</table>

Sample Output

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download