Skip to content

Instantly share code, notes, and snippets.

@stampycode
Created August 23, 2017 12:05
Show Gist options
  • Save stampycode/dd8ff98f0a09cdc350dda5ff1924e1aa to your computer and use it in GitHub Desktop.
Save stampycode/dd8ff98f0a09cdc350dda5ff1924e1aa to your computer and use it in GitHub Desktop.
Recursion-safe php variable dumper
<?php
function print_re($data, $depth = 0, $max = 5) {
if(!headers_sent()) {
header('content-type: application/json');
}
$sp = str_repeat(" ", $depth);
if(is_numeric($data)) {
echo $data;
return;
}
if(is_bool($data)) {
echo $data ? 'true' : 'false';
return;
}
if(is_null($data)) {
echo 'null';
return;
}
if(!is_object($data) && !is_array($data)) {
echo '"' . trim(var_export($data, 1), "'") . '"';
return;
}
if($depth >= $max) {
echo '"*max depth reached*"';
return;
}
if(is_object($data)) {
// Uncomment this line to get class types, but breaks JSON format
#echo '('. get_class($data) .')';
}
if($data instanceof \JsonSerializable) {
$data = $data->jsonSerialize();
}
end($data);
$last = key($data);
echo "{\n";
foreach($data as $k => $d) {
echo "$sp \"$k\": ";
print_re($d, $depth+1);
next($data);
echo ($k === $last) ? "\n" : ",\n";
}
echo "$sp}";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment