Skip to content

Instantly share code, notes, and snippets.

@lithrel
Last active April 27, 2021 07:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lithrel/a224edb1ed2975992c73 to your computer and use it in GitHub Desktop.
Save lithrel/a224edb1ed2975992c73 to your computer and use it in GitHub Desktop.
var_export with short array notation, array alignement and custom indentation
<?php
function prettyVarExport($var, array $opts = [])
{
$opts = array_merge(['indent' => '', 'tab' => ' ', 'array-align' => false], $opts);
switch (gettype($var)) {
case 'array':
$r = [];
$indexed = array_keys($var) === range(0, count($var) - 1);
$maxLength = $opts['array-align'] ? max(array_map('strlen', array_map('trim', array_keys($var)))) + 2 : 0;
foreach ($var as $key => $value) {
$key = str_replace("'' . \"\\0\" . '*' . \"\\0\" . ", "", prettyVarExport($key));
$r[] = $opts['indent'] . $opts['tab']
. ($indexed ? '' : str_pad($key, $maxLength) . ' => ')
. prettyVarExport($value, array_merge($opts, ['indent' => $opts['indent'] . $opts['tab']]));
}
return "[\n" . implode(",\n", $r) . "\n" . $opts['indent'] . "]";
case 'boolean':
return $var ? 'true' : 'false';
case 'NULL':
return 'null';
default:
return var_export($var, true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment