Reputation:
This php code shows me the content of a directory on my website:
<?php
$dir = opendir(getcwd());
?>
<body>
<table>
<tbody>
<tr>
<?php
while (($file = readdir($dir)) !== false) {
{
echo "<td>". $file ."</td>";
}
}
closedir($dir);
?>
</tr>
</tbody>
</table>
</body>
It puts the results in a table
.
The problem is that the PHP code generates a <td>
tag and store the results in it. So the final table
has one <tr>
and as many <td>
tags as there are results.
What I want to have is a table
with 3 columns (3 td) per each line (tr tag).
Is there a way to make the table dynamic and for each third <td>
tag turns to be a <tr>
tag
so the results look like this: (click here)
Instead of looking like this: (click here)
Upvotes: 0
Views: 249
Reputation: 6615
you can use modulus to keep track of where you are in the loop. Then, when you've hit a multiplication of 3, you restart the table row:
<?php
$dir = opendir(getcwd());
?>
<body>
<table>
<tbody>
<tr>
<?php
$counter = 0;
while (($file = readdir($dir)) !== false) {
{
if($counter % 3 == 0 && $counter != 0) echo "</tr><tr>";
echo "<td>". $file ."</td>";
$counter++;
}
}
closedir($dir);
?>
</tr>
</tbody>
</table>
</body>
Upvotes: 1
Reputation: 15338
try this:
<?php
$dir = opendir(getcwd());
?>
<body>
<table>
<tbody>
<?php
$n = 0;
while (($file = readdir($dir)) !== false) {
{
if($n%3 == 0){echo "<tr>";}
echo "<td>". $file ."</td>";
$n++;
}
}
closedir($dir);
?>
</tbody>
Upvotes: 4