Skip to content

Instantly share code, notes, and snippets.

@filiphazardous
Created March 25, 2022 09:56
Show Gist options
  • Save filiphazardous/c8d1112e34881dc3733fbfd05c65627d to your computer and use it in GitHub Desktop.
Save filiphazardous/c8d1112e34881dc3733fbfd05c65627d to your computer and use it in GitHub Desktop.
Limited recursion print_r re-implementation
<?php
/**
* Useful util func for debugging PHP. When var_dump and print_r blows the stack, I use this instead.
* Eg: die("<pre>".preg_replace("/</", "&lt;", safe_print_r($my_bloated_circular_object))."</pre>");
* Heavily inspired by the comments on: https://www.php.net/manual/en/function.print-r.php
*/
function safe_print_r($data, $nesting = 6, $indent = '')
{
$in = ' ';
if (!is_object($data) && !is_array($data)) {
return print_r($data, TRUE) . "\n";
} elseif ($nesting < 0) {
return "** MORE **\n";
} else {
$retVal = ucfirst(gettype($data)) . " (\n";
foreach ((array)$data as $k => $v) {
$retVal .= $indent . "${in}[$k] => " . safe_print_r($v, $nesting - 1, "${indent}${in}");
}
$retVal .= "$indent)\n";
return $retVal;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment