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

/ PHP / by Paul Robinson / 2 Comments
This post was published back on March 9, 2009 and may be outdated. Please use caution when following older tutorials or using older code. After reading be sure to check for newer procedures or updates to code.

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:

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:

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

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.

2 Comments

Author’s gravatar

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)

Reply
Author’s gravatar

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. 😉

Reply
Older Comments
Newer Comments

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

I'll keep your WordPress site up-to-date and working to its best.

Find out more