tags:

views:

362

answers:

9

How can I print the array in a Tree-like format--making it easier to read?

+1  A: 

I found it's a good idea to print_r as follows

printf("<pre>%s</pre>", print_r($array, true));

It may not be ideal, but it's easier to read.

pavium
You need the second argument to print_r to be boolean true for it to return the value and not just print it out.
Marko
Yes! that's right.
pavium
+10  A: 

Are you wrapping the output in <pre> tags? That should get you pretty decent output, because it will show the spaces. Another option would be to install the xdebug extension, which then can replace var_dump so that it generates more-readable HTML output.

notJim
+1 for xdebug. The replacement `var_dump` it provides supports arrays very nicely, almost eliminating the need for `print_r` entirely.
Alex Barrett
A: 

Mabe the output looks like junk in the webpage. Try looking at the source of the page and it will be in tree-like format I suppose.

Philipe Fatio
+4  A: 

Try:

<pre><?php print_r($var); ?></pre>

It will give the proper tree structure that HTML's whitespace policy trims out.

The Wicked Flea
As an addenda, I'll point out that I find that `<pre><?php print_r($var,true); ?></pre>` gives more consistent (tree-like) results (though I haven't researched *why* that is)
David Thomas
+3  A: 
function pr($var)
{
    print '<pre>';
    print_r(htmlspecialchars($var));
    print '</pre>';
}

pr($myArray);
John McCollum
`htmlspecialchars` please. OK, so security isn't a concern for debugging code (though escaping certainly a habit you should always have), but any ‘<’ characters in your variables will mess up the output.
bobince
`function pr($var) { print '<pre>' . htmlspecialchars(print_r($var, true)) . '</pre>'; }`
eyelidlessness
Fair enough, can't say it's ever happened to me, but thanks for pointing it out.
John McCollum
+1  A: 

Try taking a look at Zend_Debug, a relatively plug-and-play module from the Zend Framework which does an excellent job at effectively dumping complex variables.

Usage:

$my_var = new StdObject(); // or whatever
Zend_Debug::dump($my_var); 
die; // optional, prevents routing, forwarding away, etc.
Robert Elwell
A: 

May i suggest using var_export($array)?

It formats values with parsable php syntax

And even when you forget to output "<pre>" and "</pre>" tags, while not very easy on the eye, its output still makes more sense then print_r informal bunch of data.

ZJR
A: 

As many people previously mention, make sure to wrap it around a <pre> tag.

I would take an extra precautions to make sure nothing is wrapping that <pre> as well, such as <p> or <div> with a CSS class that can override the Pre's Style

Anraiki
A: 

or you could print it into the error log:

error_log(print_r($myarray,1));

will put it into you error log Note that you will see \n instead of carriage returns because it has to be collapsed in a single line.

golemwashere