Alternative var_dump for PHP, which allows you to limit the depth of nested arrays

I am trying to use var_dump on the command line with phpsh to get debugging information about some variable. But the variable contains a very deeply nested data structure. Thus, using var_dump by default displays too much information.

I want to limit the output depth level of var_dump. I found that the implementation of XDebug var_dump allows you to limit the depth, as described here: http://www.giorgiosironi.com/2009/07/how-to-stop-getting-megabytes-of-text.html

Unfortunately, I could not complete this work. I do not yet know the reason for this. I am looking for if there are alternative var_dump implementations.

+7
source share
4 answers

Check this:

function print_array($array,$depth=1,$indentation=0){ if (is_array($array)){ echo "Array(\n"; foreach ($array as $key=>$value){ if(is_array($value)){ if($depth){ echo "max depth reached."; } else{ for($i=0;$i<$indentation;$i++){ echo "&nbsp;&nbsp;&nbsp;&nbsp;"; } echo $key."=Array("; print_array($value,$depth-1,$indentation+1); for($i=0;$i<$indentation;$i++){ echo "&nbsp;&nbsp;&nbsp;&nbsp;"; } echo ");"; } } else{ for($i=0;$i<$indentation;$i++){ echo "&nbsp;&nbsp;&nbsp;&nbsp;"; } echo $key."=>".$value."\n"; } } echo ");\n"; } else{ echo "It is not an array\n"; } } 
+1
source

Here is the function for this problem:

 function slice_array_depth($array, $depth = 0) { foreach ($array as $key => $value) { if (is_array($value)) { if ($depth > 0) { $array[$key] = slice_array_depth($value, $depth - 1); } else { unset($array[$key]); } } } return $array; } 

Use this function to split the array to the depth you need, than just var_dump() or print_r() sliced ​​array :)

+5
source

I just plug this var_dump alternative:

https://github.com/raveren/kint

obviously, depth limits are supported and enabled by default. You can, in addition, overcome it on the fly, the prefix Kint::dump($var); using + - +Kint::dump($var); will not truncate in depth.

+1
source

json_encode takes a depth argument. Do it:

echo '<pre>' . json_encode($your_array, JSON_PRETTY_PRINT, $depth) . '</pre>';

+1
source

All Articles