Debugging PHP the print_r way

It’s bug crunching season and it’s time to break out that debugger. Today’s weapon of choice: mum’s old-fashioned print statements.

“Now why would you ever use something like that!?” you ask. After all, we have all been taught in school that debug print statements are inherently bad: they change the flow of logic, introduce more opportunities for human error, and you even have to remember to remove them afterwards. We all know no one cleans up after themselves these days (how else would log files grow to be gigs in size? For the record, the largest log file we encountered was over 7 gigs huge).

One answer to this question is obvious: people are lazy. With a scripting language like PHP, you can instantly refresh your sent POST form to have all of the values populated again, but this time with your print statements included. And with tools like SVN to double-check your changes before you commit, developers have a safety net for their memory lapses.

Laziness aside, let us take a look at some reasons why you might want to debug PHP without a full-fledged debugger.

print_r Debugging: pros and cons

In PHP scripts, the print_r method was introduced to display human-readable information about PHP objects and arrays for the purposes of debugging. The output comes in the form of an indented tree, which indicates when an object has properties that refer to other objects (or arrays that contain nested arrays). This is illustrated in the following output of executing the command: print_r($dummy_array);

    [hello] => world
    [foo] => Array
            [0] => b
            [1] => a
            [2] => r

Now while we won’t go as far as advocating print_r as the better debugging alternative, this ‘flattened’ array does have certain advantages over standard IDE debuggers.

Thumbs up

A big plus, in my opinion, comes from the ability to immediately work backwards from any large, unfamiliar object structure. This is akin to saying: “It works great for people who have absolutely no idea what they’re looking for!” The field you may be looking for could be buried underneath an object structure with a hierarchy depth that goes twelve levels down. To the developer venturing deep into unexplored territory, this is very much a guess-and-check clicking game with the debugger to see which of the hundreds of collapsable property names hits the jackpot.

This happened to me recently when I was investigating a mysterious issue with an unexpected NuSOAP response. I knew that the POST request headers were being stored somewhere within NuSOAP’s client object, but had no idea under what property name. After a frustrating (but brief) clickfest, I quickly changed over to a print_r display that allowed me to use the browser’s search function to jump directly to the desired field – in this case, it contained a header, such as “Content-Type”.

Eclipse debugging NuSOAP

When dozens of fields are collapsed, it is hard to find what you're looking for.

print_r debugging NuSOAP

print_r displays the entire output array fully expanded for easy searching.

For any situation where the API for a library you use may be missing or insufficiently documented, knowing where your value is in the overall object structure can help you backtrack through unfamiliar source code and to figure out the culprit. In another case study, Angie Byron from Lullabot effectively demonstrates how debugging obscure error messages in Drupal can be greatly facilitated with print_r.

A pet peeve that I have run into on several occasions with PHP debuggers (such as the one included in Eclipse for PHP Developers) is that they often truncate the output of long expressions, without providing any way to view or copy the full-length text. The majority of these debuggers also do not provide for a method to flexibly search through an object’s properties and values. print_r addresses both of these issues with its ability to fully search for a text phrase anywhere within the output array.

print_r is a lifesaver for debugging non-optimal solutions where a large portion of the code is stored in a database. Whether it’s custom PHP code stored in nodes, or Drupal triggers and rules that make use of PHP code, both of these cases are often tremendously difficult to debug through a standard PHP debugger. In these cases, it is not unusual to have access to certain objects as arguments, but the values and attributes contained in them are often unknown. print_r’s ability to take in mixed object types, coupled with its ability to be embedded in either a debug message on an HTML page or a log file on the server, make it an indispensable debugging tool.

Thumbs down

There are always two sides to the coin, and print_r comes with a few drawbacks of its own.

For instance, if print_r is invoked after the HTML page generation has been started, you will need to manually wrap <pre> tags around your print_r output, or your browser may render the entire print_r array on a single line.

    echo "<pre>" . print_r($foo_array, TRUE) . "</pre>"; // pass in special parameter to return the output, rather than print it 

When your object does indeed have a dozen nested levels of objects, it’s also quite difficult to differentiate between one nested level and another. One level may contain a score of variables that span four pages, after which you’ve lost the nesting context that is critical to understanding the relationships between objects.

Finally, you just cannot be sure what type of object is being displayed on the screen. Is that value of [foo] => 1 pointing to the string ’1′ or an integer? Does [foo] => denote an empty string, or a string containing spaces that you just can’t see without selecting it with your mouse?

Krumo to the rescue

These are some very major concerns that could ward off even the most curious of developers. Thankfully, there is an open source solution called Krumo that addresses all of these issues.

Krumo behaves similarly to print_r: you pass in a mixed variable type such as an array or an object and it outputs a human-readable tree, rendered in a browser-friendly format. The tree is fully expandable, and each node which contains child elements can be expanded or collapsed as desired. In addition to the actual value, each element in the tree also indicates its type (such as string or integer) and type-specific information (the number of characters in a string, for instance, or the element count for an array).

Krumo output for the superglobal $_SERVER

Krumo output for the superglobal $_SERVER; highlighted nodes can be toggled for more information.

Additionally, Krumo’s output tree is fully themable, and the default Krumo package comes pre-installed with a handful of skins.

On top of the page space-saving design, Krumo’s power comes from the plethora of helper methods that can be invoked. This includes, but is certainly not limited to:

  • displaying a debug backtrace,
  • listing all included functions and files,
  • viewing the contents of any superglobal,
  • outputting the list of configuration settings from php.ini (or any .ini file), and even
  • enabling or disabling Krumo globally.

For a more complete list of functions, check out the examples section and the krumo class documentation.

How to setup Krumo

Krumo can be setup on just about any PHP framework or CMS of choice. This section briefly groups together a handful of resources to help you get started.

With Drupal

Krumo automatically comes with all default Drupal 6 installations. All you need to do is to enable the Devel module1.

Basic troubleshooting:
If you’re getting the standard White Screen of Death from your browser when you execute Krumo functions, you should double-check to make sure the Devel module is enabled. It is not uncommon for the Devel module to be toggled on and off during a development lifecycle. Also, krumo() output is only visible to super administrators, so if you want to view Krumo output on another user for development purposes, be sure to give that user’s role the “access devel information” permission.

Additional resources:
Krumo, a PHP debugging tool that I’m using in Drupal @
Using Krumo with Devel @
Krumo module @

With WordPress

The WP-Devel developer toolbar allows developers to easily debug information across their website. Setting this up is as easy as uploading and activating the plugin. As with Drupal, only site administrators will be able to view the toolbar and debugging information.

The WP-Devel plugin builds on top of Chris Poteet’s WP-Debug plugin, which was one of the first plugins to integrate Krumo with WordPress.

Additional resources:
Ease PHP (WP as well) learning and debug with Krumo @

With CakePHP

Stacy Pawlowich’s tantalizing tutorial Sexy Cake with Krumo: Say Goodbye to print_r() will see you on your way to Krumoing in your views.

Extending Krumo

While Krumo on its own is a great debugging tool, it is still missing some features that might make your debugging session less painful than it needs to be. For instance, it would be nice if all Krumo panels were fully expanded so the browser can jump to any value without needing to toggle each node first.

Thankfully, with some jQuery magic, this can be done with minimal effort. Just place this on any page that contains a Krumo array:

<script type="text/javascript">
$(".krumo-root div.krumo-element.krumo-expand").each(function(index,Element) {

Other basic customizations could include setting a default output width so that Krumo only occupies a certain portion of the page, or using jQuery’s .after() function to append a search box that can expand all nodes that contain a certain keyword.

Ending Remarks

In this article, we have seen how the power and flexibility from Krumo, a human-readable wrapper around print_r and var_dump, can turn an ordinary PHP developer into a rock star PHP developer. It allows you to easily view the contents of variables and superglobals, included files and interfaces (and much more), in an easy-to-use collapsable debugger that is embedded right within the HTML page so you can see the page in its entirety.

A word of caution: Krumo, by no means, is a substitute for a good debugger of any kind. There are a plethora of cases when jumping to a breakpoint and walking through the coded logic is exactly what will solve the problem. If a table cell fails to render properly, say, while iterating through hundreds of rows in a Drupal-rendered view, a PHP debugger that has conditional breakpoints2 will get you to the root cause faster than searching through the browser could, plus it will save you the time it would take for your browser to render the hundreds of rows to begin with.

Knowing which method of debugging is the most efficient for your situation is what will save you the most time in the long run.


  1. PHP: print_r – Manual
  2. Quick-and-Dirty Debugging @ Lullabot
  3. Debugging @ Software Carpentry, especially the section “What’s Wrong with Print Statements”
  4. Krumo: Version 2.0 of print_r(); and var_dump(); (download) (official documentation)
  5. Krumo @
  6. WordPress › WP-Devel « WordPress Plugins
  7. .each() – jQuery API, the jQuery function of the day
  1. Note: Since the Devel module is required, you will not be able to execute krumo calls when logged in as users who cannot access Devel functionality.
  2. Eclipse for PHP Developers is an IDE that does a good enough job at this. Plus it’s free.
  1. Hi,

    I am the developer of Krumo, and I just want to thank you for this post and all the wonderful stuff you said about my project. I am really happy that people are still finding it useful, no matter that I haven’t got time to continue working on it: it’s latest update is from probably late 2007. Anyway, it is on my todo list ;)

    Oct 16th, 2010
  2. Hi Kaloyan,

    The fact that Krumo is automatically included in several major open source PHP systems attests to its ongoing usefulness after all this time.

    Thanks for creating this handy debugger – it belongs in every PHP developer’s toolkit!

    David Chang
    David Chang
    Oct 18th, 2010

Add a comment

Comment feed
The better to greet you with
No one will ever see this
Your pride and joy
The reason this comment form exists

The crew behind ASOT

We're a team of interactive, software, and business intelligence experts skilled in the design, construction, and management of online enterprise systems.

Visit The Jonah Group site

Get in touch with us