How can PHP be optimized to output HTML tables efficiently and effectively?

To optimize PHP for outputting HTML tables efficiently, it is important to minimize the number of loops and conditional statements used to generate the table structure. One effective way to do this is by using a nested loop to iterate over the data and output rows and columns accordingly. Additionally, utilizing functions or classes to encapsulate table generation logic can help improve code readability and maintainability.

<?php
// Sample data for demonstration
$data = [
    ['Name', 'Age', 'Country'],
    ['John Doe', 25, 'USA'],
    ['Jane Smith', 30, 'Canada'],
    ['Alice Johnson', 22, 'UK']
];

// Function to generate HTML table from data
function generateTable($data) {
    echo '<table>';
    foreach ($data as $row) {
        echo '<tr>';
        foreach ($row as $cell) {
            echo '<td>' . $cell . '</td>';
        }
        echo '</tr>';
    }
    echo '</table>';
}

// Output the HTML table
generateTable($data);
?>