I just want to create a table on HTML with a PHP loop. So, I try to do this:
<table id="tdesign">
<thead>
<tr>
<th>No</th>
<th>Nama</th>
<th>Kelas</th>
</tr>
</thead>
<tbody>
<?php $no = 1; ?>
<?php $kls = 10;?>
<?php for ($i=1; $i <= 10 ; $i++) :?>
<tr>
<td><?php echo $no++; ?></td>
<td>Name <?php echo $i; ?></td>
<?php endfor; ?>
<?php for ($j=10; $j >= 1 ; $j--) : ?>
<td><?php echo "Class ". $j . "n" ;?></td>
<?php endfor; ?>
</tr>
</tbody>
</table>
But, why the output becomes this?
3
Answers
It’s because you’ve got a loop inside a loop.
Try this instead:
Assuming that you really need two nested loops.
You need to move the
endfor
to the end of the loop, otherwise there will be<tr>
before the 2nd loopSo
Assuming you have an array like this:
My table loop will be look like this:
You must put the tbody contents (tr, td) inside the loop