Home > Tutorials > PHP > PHP Tip #1: Formating Array & Object Output When Debugging
Permalink to PHP Tip #1: Formating Array & Object Output When Debugging

PHP Tip #1: Formating Array & Object Output When Debugging

by on 03.09.2009 | 2 comments

This is the first in a series of posts I’m doing on small tips which help when coding with PHP. The first is a one [...]

This is the first in a series of posts I’m doing on small tips which help when coding with PHP. The first is a one most devs probably know, but novice or new coders may not know and probably should.

When working with arrays and/or objects you may sometimes need to see what is held in them, so you throw that array through print_r() and end up with something like the following:

Array ( [1] => one [2] => two [3] => three [4] => four )

This is a simple array, but if you have a complex one that has a huge amount of data in you can easily lose track of everything. To make it easier to read just echo out a pre tag around the print_r(). Like this:

echo '<pre>';
print_r($array);
echo '< /pre>'; //remove the space before the '/'

Since PHP generates the output pre-formatted the pre tags allow the info to be shown like it should, which is like this:

Array
(
    [1] => one
    [2] => two
    [3] => three
    [4] => four
)

See much neater & a lot easier to read. :) This also works with the output of objects, hence the title.

Hope that helps someone & there will be more PHP tips as well as other tutorials coming soon. If you have any comments or questions you can leave them below.

Written by Paul Robinson

A Web coder in languages such as CSS, X/HTML, jQuery, but mostly PHP. Addicted to Girls Aloud, Jennifer Morrison, Carah Faye Charnow, TV Show Chuck, and completely in love with Yvonne Strahovski's smile.

Give something back!

If you LOVED this tutorial and would like to show your appreciation, please consider or a little something from our Amazon Wishlist.

Discussion: 2 Comments

  1. Apr 4th, 2009 @ 16:14:58

    I cannot stress how incredibly useful this tag is.
    I used to debug with print_r then view source, then I discovered this delight :)
    Only minor warning is that it flows outside of boundaries (e.g. In a div of fixed width the text will flow out beyond that width if necessary)


  2. Apr 4th, 2009 @ 16:25:30

    Yep, it’s very useful. The <pre> tag will flow out of containers mainly because it is a preformatted block element.

    Since you don’t usually keep the info on the page for everyone to see it isn’t usually a problem, although if you really want to you could set some CSS styles to have a fixed width on the pre tag & set overflow to auto & a scrollbar will appear if it becomes too big. ;)


Leave a comment

Please enclose code in [lang] tags. For example [php] echo 'hello world'; [/php]

* Name, Email, Comment are Required