How can PHP scripts dynamically handle changing array or database table structures for visual output on a webpage?

When dealing with changing array or database table structures for visual output on a webpage, one solution is to dynamically handle the structure by using loops to iterate through the data and generate the visual output accordingly. By dynamically accessing and displaying the data elements based on their structure, the PHP script can adapt to changes without needing manual adjustments.

// Sample PHP code snippet for dynamically handling changing array structures

$data = [
    ['name' => 'John', 'age' => 25],
    ['name' => 'Jane', 'age' => 30, 'city' => 'New York'],
    ['name' => 'Bob', 'age' => 22, 'city' => 'Los Angeles', 'occupation' => 'Engineer']
];

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

foreach ($data as $row) {
    echo '<tr>';
    foreach ($row as $value) {
        echo '<td>' . $value . '</td>';
    }
    echo '</tr>';
}
echo '</table>';