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 [...]

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.