PHP Tip #1: Formating Array & Object Output When Debugging
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:
1 |
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:
1 2 3 |
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:
1 2 3 4 5 6 7 |
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.
2 Comments
Kit Barnes
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)
Veneficus Unus
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. 😉