What are the best practices for structuring PHP code to generate a table with multiple columns?
When generating a table with multiple columns in PHP, it is best practice to separate the HTML structure from the PHP logic by using a loop to iterate over the data and generate the table rows dynamically. This approach allows for easier maintenance and scalability of the code.
<table>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
<?php
// Sample data for demonstration purposes
$data = [
['value1', 'value2', 'value3'],
['value4', 'value5', 'value6'],
['value7', 'value8', 'value9']
];
foreach ($data as $row) {
echo "<tr>";
foreach ($row as $value) {
echo "<td>$value</td>";
}
echo "</tr>";
}
?>
</table>