How can PHP scripts be optimized to generate compact and efficient HTML code for tables?

To optimize PHP scripts for generating compact and efficient HTML code for tables, one approach is to use loops efficiently to generate table rows and columns dynamically. This can help reduce redundancy in the code and make it easier to manage and update. Additionally, consider using functions or classes to encapsulate table generation logic, making the code more modular and reusable.

<?php
// Sample PHP code snippet for generating a compact and efficient HTML table using loops

// Sample data for the table
$data = [
    ['Name', 'Age', 'City'],
    ['John', 25, 'New York'],
    ['Alice', 30, 'Los Angeles'],
    ['Bob', 22, 'Chicago']
];

// Start the table
echo '<table>';

// Loop through the data to generate table rows and columns
foreach ($data as $row) {
    echo '<tr>';
    foreach ($row as $cell) {
        echo '<td>' . $cell . '</td>';
    }
    echo '</tr>';
}

// End the table
echo '</table>';
?>