How can PHP beginners avoid repeating headers for each row when displaying query results in a table?

When displaying query results in a table, PHP beginners can avoid repeating headers for each row by using a conditional statement to only display the headers once at the beginning of the table. By checking if the headers have already been displayed, you can ensure that they are only printed once.

<?php
// Assuming $results is the array of query results

echo "<table>";
echo "<tr>";
foreach($results[0] as $key => $value) {
    echo "<th>$key</th>";
}
echo "</tr>";

foreach($results as $row) {
    echo "<tr>";
    foreach($row as $value) {
        echo "<td>$value</td>";
    }
    echo "</tr>";
}
echo "</table>";
?>