Skip to content

Instantly share code, notes, and snippets.

@herdianf
Last active July 17, 2022 10:19
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 herdianf/5c86b4be9fb8563ed2d3a4e9a491b391 to your computer and use it in GitHub Desktop.
Save herdianf/5c86b4be9fb8563ed2d3a4e9a491b391 to your computer and use it in GitHub Desktop.
PHP print_r without circular issues and limited by depth
<?php
/**
* Function to dump variables limited by depth and without circular issues.
*
* @param $thing The object.
* @param int $maxdepth Maximum depth to recurse.
* @param array $stack Stack to store the previous object. Ignore this.
* @param int $depth The current depth. Ignore this.
*/
function print_rr($thing, $maxdepth = 3, $stack = [], $depth = 0) {
$type = 'array';
if (is_object($thing)) {
$vars = get_object_vars($thing);
$type = get_class($thing);
} else {
$vars = $thing;
}
$prefix = str_repeat(" ", $depth);
if (is_array($vars)) {
$stack[] = $thing;
$count = $type === 'array' ? '(' . count($vars) . ')' : '';
if ($depth <= $maxdepth) {
echo "$type$count => [";
if (count($vars) == 0) {
echo "]\n";
}
else {
foreach ($thing as $k => $v) {
if (!empty($stack) && in_array($v, $stack)) {
echo "\n$prefix $k => [circular]\n";
} else {
echo "\n$prefix $k => ";
print_rr($v, $maxdepth, $stack, $depth + 1);
}
}
echo "$prefix]\n";
}
} else {
echo "$type$count => [omitted]";
}
return;
}
var_dump($thing) . "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment