What are some best practices for handling varying column lengths in a table output using PHP?

When displaying data in a table output using PHP, one common issue is handling varying column lengths. To ensure that the table looks neat and organized, it is important to align the columns properly. One way to achieve this is by determining the maximum length of each column and padding the shorter columns with spaces to match the longest one.

$data = [
    ['John Doe', 'Developer', 'New York'],
    ['Jane Smith', 'Designer', 'Los Angeles'],
    ['Michael Johnson', 'Manager', 'Chicago'],
];

// Find the maximum length of each column
$columnLengths = array_map(function($col) {
    return max(array_map('strlen', $col));
}, array_map(null, ...$data));

// Output the table with aligned columns
echo '<table>';
foreach ($data as $row) {
    echo '<tr>';
    foreach ($row as $key => $value) {
        echo '<td>' . str_pad($value, $columnLengths[$key]) . '</td>';
    }
    echo '</tr>';
}
echo '</table>';