Skip to content

Instantly share code, notes, and snippets.

@barezina
Last active February 24, 2020 03:30
Show Gist options
  • Save barezina/dff105130583f4a070f30eef11892236 to your computer and use it in GitHub Desktop.
Save barezina/dff105130583f4a070f30eef11892236 to your computer and use it in GitHub Desktop.
PHP ascii table from 2D array
function generateAsciiTable($data)
{
// Generate row widths
$rowWidths = [];
foreach ($data as $row) {
foreach ($row as $index => $cell) {
if (!isset($rowWidths[$index])) {
$rowWidths[$index] = strlen($cell) + 2;
} else {
if ($rowWidths[$index] < strlen($cell) + 2) {
$rowWidths[$index] = strlen($cell) + 2;
}
}
}
}
// Row, go through again and repad all the things!
foreach ($data as $rindex => $row) {
foreach ($row as $cindex => $cell) {
$data[$rindex][$cindex] = str_pad(
' ' .
$data[$rindex][$cindex],
$rowWidths[$cindex],
' ',
STR_PAD_RIGHT
);
}
}
// Container for table text
$tableText = "";
// Now, output the row lines with some magic.
$headerLineLength = strlen(implode("|", $data[0]));
foreach ($data as $index => $row) {
$line = implode("|", $row);
// if header line
if ($index == 0) {
$tableText .= "\n|" . str_pad("", $headerLineLength, "-") . "|\n";
$tableText .= "|" . $line . "|\n";
$tableText .= "|" . str_pad("", $headerLineLength, "-") . "|\n";
} else {
$tableText .= "|" . $line . "|\n";
}
}
$tableText .= "|" . str_pad("", $headerLineLength, "-") . "|\n";
return $tableText;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment