Generating an HTML Table Using a Single Loop in PHP
Let's generate a table using a single loop,
manually writing the elements of the subarray
into the td tags:
<?php
echo '<table>';
foreach ($arr as $user) {
echo '<tr>';
echo "<td>{$user['name']}</td>";
echo "<td>{$user['age']}</td>";
echo "<td>{$user['salary']}</td>";
echo '</tr>';
}
echo '</table>';
?>
This method gives us more control, both over the order of the cells and the ability to add some additional data to each cell, for example, like this:
<?php
echo '<table>';
foreach ($arr as $user) {
echo '<tr>';
echo "<td>{$user['name']}</td>";
echo "<td>{$user['age']} years</td>";
echo "<td>{$user['salary']} dollars</td>";
echo '</tr>';
}
echo '</table>';
?>