Better output for print_r function

Better output for print_r function

In PHP for obtaining a visualization on the screen of the contents of a array or an object you don’t have to create a loop using a for, foreach or while but you could use a handy function named print_r.

As example if you want to print the contents of an object you could simply write

print_r($object);

and the resulting echo will be
stdClass Object ( [ID] => 1 [post_author] => 1 [post_date] => 2000-01-01 00:00:01 [post_content] => This is the content of the message. [post_title] => Message Title [post_excerpt] => This is the excerpt of the message. [post_status] => publish [post_name] => message [post_parent] => 0 [menu_order] => 0 [post_type] => post )

With a single line of code we have obtained a detailed output with all the data contained inside the object.

As you noted, even if the object in exam is composed only by a low number of basic data, the output resulting is quite messy and not easily readable. Now think if the object or the array that you have to print would be composed by hundreds of data, maybe with hierarchies inside it, the finding of information will become really hard.

For solving this inconvenience we will take advantage of a HTML tag named <pre>.

In HTML language the line break inside texts are ignored (for passing on a new line you have to use the specific tag <br>), so the print echoed by our print_r is displayed all on the same line.

Wrapping our output inside the tag <pre> (abbreviation of “preformatted”) like this

<pre>
print_r($object);
</pre>

will cause that new lines inside the output will be correctly read, obtaining a result like the following

stdClass Object
(
[ID] => 1
[post_author] => 1
[post_date] => 2001-01-01 00:00:01
[post_content] => This is the content of the message.
[post_title] => Message Title
[post_excerpt] => This is the excerpt of the message.
[post_status] => publish
[post_name] => message
[post_parent] => 0
[menu_order] => 0
[post_type] => post
)

Now the output is undoubtedly more readable: every data is on its own row and the result is also indented hierarchically, perfect!

As for print_r the same results could be obtained also for other similar functions like var_dump or var_export.

One comment on Better output for print_r function

Leave a Reply

Your email address will not be published. Required fields are marked *