Last active
April 27, 2021 07:34
-
-
Save lithrel/a224edb1ed2975992c73 to your computer and use it in GitHub Desktop.
var_export with short array notation, array alignement and custom indentation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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