PHP: A prettier way to var_dump
October 02, 2022There are various ways to dump information about a variable/object in PHP.
Typically, you'd use them in a breakpoint-y fashion by inserting some dump
function and hitting the endpoint to trigger the code. You hit the endpoint
by curl
-ing or visiting its URL, and you realize that the output is
unreadable:
^ var_dump
^ var_export
^ print_r
This happens because none of them formats the output for HTML rendering (as it shouldn't!), which makes it extra difficult to parse when you have a large object.
Here's how I make it pretty: #
1<?php
2
3function d($obj): string {
4 return highlight_string("<?php\n" . print_r($obj, true) . "\n", true);
5}
6echo(d($dogsBySize));
This embeds the output of print_r
inside highlight_string
to make it render nicely:
It's a tremendous improvement in readability. If you want to skip having to
echo()
the output, make the function dump it directly instead of returning it:
1<?php
2
3function d($obj) {
4 highlight_string("<?php\n" . print_r($obj, true) . "\n", false);
5}
6d($dogsBySize);