What alternative solutions exist for ensuring consistent column widths in a table output when using PHP?

When outputting a table in PHP, inconsistent column widths can make the table look messy and unprofessional. One solution to ensure consistent column widths is to calculate the maximum width of each column and set a fixed width for each column based on the maximum width found. This can be achieved by iterating through the data to find the maximum width of each column, and then using that information to set the width of each column in the table.

// Sample data for the table
$data = [
    ['Name', 'Age', 'Occupation'],
    ['John Doe', '30', 'Engineer'],
    ['Jane Smith', '25', 'Designer'],
    ['Michael Johnson', '35', 'Developer']
];

// Calculate the maximum width for each column
$maxWidths = [];
foreach ($data as $row) {
    foreach ($row as $key => $value) {
        $length = strlen($value);
        if (!isset($maxWidths[$key]) || $length > $maxWidths[$key]) {
            $maxWidths[$key] = $length;
        }
    }
}

// Output the table with consistent column widths
echo '<table>';
foreach ($data as $row) {
    echo '<tr>';
    foreach ($row as $key => $value) {
        echo '<td style="width: ' . ($maxWidths[$key] * 10) . 'px">' . $value . '</td>';
    }
    echo '</tr>';
}
echo '</table>';