Skip to content

Instantly share code, notes, and snippets.

@mbirth
Last active December 19, 2015 00:28
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 mbirth/5868615 to your computer and use it in GitHub Desktop.
Save mbirth/5868615 to your computer and use it in GitHub Desktop.
PHP Snippet to return a string like print_r($var, true) - but more readable and with JSON parsing
<?php
function print_r_tree(&$var, $level=0)
{
$result = '';
if (is_array($var) || is_object($var)) {
$result = gettype($var) . ' <span style="color: #aaa;">(' . count($var) . ' entries)</span>' . PHP_EOL;
foreach ($var as $key=>$value) {
$result .= str_repeat('|', $level) . '+<strong>' . $key . '</strong>: ' . print_r_tree($value, $level+1);
}
} else {
if (is_string($var)) {
$result = '"' . $var . '"';
} else {
$result = $var;
}
$result .= ' <span style="color: #aaa;">(' . gettype($var);
if (is_string($var)) $result .= ', ' . strlen($var) . ' characters';
$result .= ')</span>' . PHP_EOL;
if (is_string($var) && $var{0}=='{' && !is_null($var2 = json_decode($var, true))) {
$result .= '<span style="color: #88a;">' . str_repeat('|', $level) . '# JSON DATA: ' . print_r_tree($var2, $level) . '</span>';
}
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment