Skip to content
PHP Logo

How can PHP developers optimize their code to efficiently display data in a tabular format on a web page?

To efficiently display data in a tabular format on a web page, PHP developers can optimize their code by using a loop to iterate through the data and generate the HTML table dynamically. This approach reduces redundancy and makes the code more maintainable.

php
<?php
// Sample data
$data = [
    ['Name' => 'John Doe', 'Age' => 30, 'City' => 'New York'],
    ['Name' => 'Jane Smith', 'Age' => 25, 'City' => 'Los Angeles'],
    ['Name' => 'Mike Johnson', 'Age' => 35, 'City' => 'Chicago']
];

// Display data in a tabular format
echo '<table border="1">';
echo '<tr>';
foreach (array_keys($data[0]) as $header) {
    echo '<th>' . $header . '</th>';
}
echo '</tr>';
foreach ($data as $row) {
    echo '<tr>';
    foreach ($row as $value) {
        echo '<td>' . $value . '</td>';
    }
    echo '</tr>';
}
echo '</table>';
?>