Skip to content

Instantly share code, notes, and snippets.

@pstuifzand
Created November 16, 2021 11:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pstuifzand/25b58e25d0230f0e61ecb97994b41f65 to your computer and use it in GitHub Desktop.
Save pstuifzand/25b58e25d0230f0e61ecb97994b41f65 to your computer and use it in GitHub Desktop.
Indent PHP array as a table. Arrays and objects become tables as well
/**
* @param array $result
* @param int $depth
* @return void
*/
function var_table(array $result, int $depth = 0): void
{
$indent = str_repeat(" ", $depth * 4);
if (empty($result)) {
echo sprintf("%s<empty>\n", $indent);
}
foreach ($result as $key => $value) {
if (is_array($value) && !empty($value)) {
echo sprintf("%s%s:\n", $indent, $key);
var_table($value, $depth + 1);
} elseif (is_object($value) && !empty($value)) {
echo sprintf("%s%s:\n", $indent, $key);
var_table((array)$value, $depth + 1);
} else {
echo sprintf("%s%-20s %s\n", $indent, $key,
is_array($value) ? '<empty>' : (indent_multiline($value, 20 + 1, $depth, 4) ?? '<null>'));
}
}
}
function indent_multiline($value, $keyLength, $depth, $indent)
{
$value = str_replace(["\r\n", "\r"], "\n", $value);
$lines = explode("\n", $value);
if (count($lines) === 1) {
return $value;
}
$prefix = str_repeat(" ", $keyLength + ($depth) * $indent);
return $lines[0] . "\n" . implode("\n",
array_map(static function ($line) use ($prefix) {
return $prefix . $line;
}, array_slice($lines, 1)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment