PHP aligned plain-text CLI table renderer
PHP
<?php
function render_table(array $headers, array $rows): string
{
$widths = array_map('strlen', $headers);
foreach ($rows as $row) {
foreach (array_values($row) as $i => $cell) {
$widths[$i] = max($widths[$i] ?? 0, strlen((string) $cell));
}
}
$line = function (array $cells) use ($widths): string {
$parts = [];
foreach (array_values($cells) as $i => $cell) {
$parts[] = str_pad((string) $cell, $widths[$i]);
}
return implode(' | ', $parts);
};
$divider = implode('-+-', array_map(fn ($w) => str_repeat('-', $w), $widths));
$out = [$line($headers), $divider];
foreach ($rows as $row) $out[] = $line($row);
return implode(PHP_EOL, $out);
}