WP Ref

Using var_export to Debug and Prettify Dumps of Anything

When developing for WordPress (and anything in PHP in-fact), it can be incredibly useful to be able to dump values. Yes, there’s a function for that called var_dump, which is great… if you’re not dealing with anything complex. As soon as you output anything more complex such any type of array, object, or class instance, it’s much more difficult to read the output of var_dump on it. There are no line breaks, indents, anything to help make heads or tails out of it.

Using var_export

That’s where var_export comes in. It makes the output ready to be readable when printed, and it works on anything: arrays, objects, class instances, you name it. Here’s an example:

$posts = get_posts(); var_export( $posts, true );
Code language: PHP (php)

It’s important to set the second argument to true, telling the function to echo the output, both for display on a web page and for logging purposes.

When executed in a plugin hook, say, init, you should see the following input on every page of the site:

Screenshot of the output of var_export on a variable housing the result of a get_posts call.

If you’re echoing var_export, it’s important to encapsulate it with <pre></pre> tags so whitespace is maintained and the output is prettified.

If you want to use var_export for use cases such as logging and it’s not going to be output on a web page, then you don’t need to encapsulate it in <pre></pre> tags. The dump should be logged in prettified format automatically.

In Conclusion

The var_export PHP function is so useful, whether debugging any value, large or small. I have found functions like var_export invaluable to keep in my toolbox and use them frequently.


Posted

in

by

Tags:

Need WordPress development services?

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *