As WordPress programmers, we often need to peek under the hood at what is going on including what value a variable has at a given time. I’ve gone through a lot of iterations of how I peek under the hood. These are two quick ways that are available to me on any site I work on.
|# output $x (can be an object or array)|
|# to your page, nicely formatted|
|print_r( $x );|
|# record $x (can be an object or array)|
|# in your PHP error log|
|error_log( print_r( $x, true ));|
It all started with echo
Originally I found
echo was the easiest way to inspect a variable. As I worked on my WordPress Theme, I’d write
echo $x; and the value would appear on the page. This was perfect as long as
$x was something simple like a string, integer, or a floating point number. Unfortunately, some of my echo statements were returning “Array” or worse yet, nothing. Unfortunately,
echo chokes on more complex variables like objects and arrays.
print_r, echo for complex things
Then I was introduced to
print_r( $x );, which spits out the object and all the properties within it. This works for objects and arrays.
Unfortunately, it looked like this on my page
Making print_r pretty
It turns out that
print_r actually spits out everything nicely formatted but the HTML parsing makes a hash of it. To see the nicely formatted output, I would View Source on the page but an extra click is never any fun. Fortunately, some programmer smarter than I thought to wrap the output in HTML
<pre> tags and this knowledge made its way to me.
I feel pretty. Oh so pretty
WordPress Debug Error Log with print_r
The PHP function
error_log() allows you to write to your php_error.log. This is nice because now you can get to the information you want without mucking up your actual page output. The rub is
print_r() outputs a string rather than returning it, preventing you from writing it to your php_error.log.
Once again, the collective knowledge of programmers on the Internet helped me learn that
print_r() can take a second parameter, a bool that indicates whether the result should output or be returned.
error_log( print_r( $x, true ) ); records your nicely formatted output in your WordPress php_error.log
In the interest of full disclosure, before
print_r() I was using the more obviously named
var_dump(), which does almost exactly the same thing as
print_r() but does not accept a parameter to return the value instead of outputting it.
This led to a ridiculous hack where I wrote a function that wrapped
error_log( ob_get_contents() ); in-between. Though embarrassing, this serves as a nice reminder that I can usually refactor my code to be much cleaner.