⊗ppPmSFNLT 284 of 447 menu

Generating an HTML Table Using Two Nested Loops in PHP

Let's form our table using two nested loops:

<?php echo '<table>'; foreach ($arr as $row) { echo '<tr>'; foreach ($row as $cell) { echo "<td>$cell</td>"; } echo '</tr>'; } echo '</table>'; ?>

This method is convenient because there is no need to write out each cell of the table separately. However, a disadvantage of this approach is the loss of control.

Nevertheless, control can be regained with the help of conditions, like this:

<?php echo '<table>'; foreach ($arr as $row) { echo '<tr>'; foreach ($row as $key => $cell) { if ($key === 'salary') { echo "<td>$cell dollars</td>"; } else { echo "<td>$cell</td>"; } } echo '</tr>'; } echo '</table>'; ?>

Our code can be simplified as follows:

<?php echo '<table>'; foreach ($arr as $row) { echo '<tr>'; foreach ($row as $key => $cell) { if ($key === 'salary') { $cell .= ' dollars'; } echo "<td>$cell</td>"; } echo '</tr>'; } echo '</table>'; ?>

The following array is given:

<?php $products = [ [ 'name' => 'product1', 'price' => 100, 'amount' => 5, ], [ 'name' => 'product2', 'price' => 200, 'amount' => 6, ], [ 'name' => 'product3', 'price' => 300, 'amount' => 7, ], ]; ?>

Form an HTML table using it.

byenru