Skip to content

Instantly share code, notes, and snippets.

@luchaninov
Last active August 29, 2015 14:06
Show Gist options
  • Save luchaninov/08034844d5820c3672cf to your computer and use it in GitHub Desktop.
Save luchaninov/08034844d5820c3672cf to your computer and use it in GitHub Desktop.
pretty var_export
<?php
function php_encode($data)
{
if (is_string($data)) {
return '\'' . $data . '\'';
}
if (!is_array($data) && !is_object($data)) {
return $data;
}
$isNumericalKeys = true;
$keys = array_keys($data);
for ($i = 0; $i < count($keys); $i++) {
if ($keys[$i] !== $i) {
$isNumericalKeys = false;
break;
}
}
$result = [];
$result[] = '[';
foreach ($data as $key => $value) {
if (is_string($key)) {
$key = '\'' . $key . '\'';
}
$value = php_encode($value);
$value = str_replace("\n", "\n ", $value);
$prefix = (!$isNumericalKeys) ? $key . ' => ' : '';
$result[] = ' ' . $prefix . $value . ',';
}
$result[] = ']';
return implode("\n", $result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment