Creating dynamic HTML table in PHP : Easy and Simple tutorial

Problem:

I want to create a dynamic HTML table with a row starting after certain number of columns, i.e. like, i want to create an html table which automatically generate new row after 3 columns in a row.

Solution:


$content = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
<table border="1" width="50%">
<tr>
<?php 
$counter = 0;
foreach($content as $data) {
    if($counter != 0 && $counter%3 == 0) {
?>
    </tr><tr>
<?php 
    }
?>
    <td>
        <?php echo $data; ?>
    </td>
<?php
    $counter++;
} 
?>
</tr>
</table>

Here, $content is an array of 9 numbers (1 to 9). The array value can be any. You can have your custom array with your custom values. I have looped through the array and printed data in a html table. I have created new row after 3 columns have been created.

Hope it helps.
Thanks.