Created
March 25, 2022 09:56
-
-
Save filiphazardous/c8d1112e34881dc3733fbfd05c65627d to your computer and use it in GitHub Desktop.
Limited recursion print_r re-implementation
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 | |
/** | |
* Useful util func for debugging PHP. When var_dump and print_r blows the stack, I use this instead. | |
* Eg: die("<pre>".preg_replace("/</", "<", 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