Tuesday, May 13th, 2008

Formatting Debug Output with print_r()

By Arc90

PHP’s built in debugging functions, var_dump and print_r, are great for displaying a structured representation of a complex object or array and for viewing data printed to stdout. But what if you want to write that information to a log file?

There are a few decent recursive functions that iterate through the array or object. But there’s really nothing quite like the format provided by print_r.

Many programmers don’t realize that you can supply the print_r function with a second boolean argument. When set to TRUE (example below), debugging output will be not be rendered to stdout, which allows you to save it to a variable instead.

$complexDebug = print_r($_SERVER, TRUE);
error_log($complexDebug);

The previous code will take the print_r output of the SERVER array and save it as a string to the ‘complexDebug’ variable.The second line writes the string (preserving its format) to the error log file.

One Response

  1. root said:

    thanks for the tip, print_r has been giving me trouble today, guess i need to check arguments closer :(

Leave a Comment