Create multiple HTML tables with PHP for loop

Posted by Shek on June 22, 2010 under PHP | Be the First to Comment | Total View: 7,763 views

Editor’s note: To create one HTML table is easy, but to create multiple HTML tables, We have to copy and paste the code many times. However we could do the job with a PHP for loop.

Here are the steps:

  1. First we create a PHP variable $numoftable which indicate the number of HTML tables you want to create. In this example, we are going to create 5 HTML tables:
    <?php $numoftable = 5; ?>
  2. We then create a for loop with to repeat the code of a HTML tables:
    <?php
    $numoftable = 5;
    for($i=0; $i<$numoftable; $i++){?>
    ............
    <?php } ?>
  3. Then we put the HTML table code inside the for loop. The code will repeat itself when $i less then $numoftable. Because $i = 0 in the beginning, and $i will add 1 to itself, it will keep looping as far as it is less than 5. In this case the HTML table will repeat itself 5 times:
    <?php
    for($i=0; $i < $numoftable; $i++){?>
    <table border="1">
    <tbody>
    <tr>
    <td>1</td>
    <td>2</td>
    </tr>
    </tbody>
    </table>
    <?php } ?>

All together:

<?php
$numoftable = 5;
for($i=0; $i < $numoftable; $i++){?>
<table border="1">
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
</tbody>
</table>
<?php } ?>

So we get from this example is 5 HTML tables.

Not what you want? Try a Search

Add A Comment

*