如果我在PHP中使用print_r,它会在垃圾中打印数组

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

Try:

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

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

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.

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.

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.

function pr($var)
{
    print '<pre>';
    print_r(htmlspecialchars($var));
    print '</pre>';
}

pr($myArray);

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.

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.

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

You could print it into the error log:

error_log(print_r($myarray,1));

Note that you will see instead of carriage returns because it has to be collapsed in a single line.