PHP: A prettier way to var_dump
— #php, #debugging
var_dump is ugly: #
Here's how you can make it pretty: #
Use print_r, and embed
the output inside
highlight_string.
<?php
function d($obj): string { return highlight_string("<?php\n" . print_r($obj, true) . "\n", true);}echo(d($dogsBySize));
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:
<?php
function d($obj) { highlight_string("<?php\n" . print_r($obj, true) . "\n", false);}d($dogsBySize);Alternatives #
If you use var_dump a lot, check out Xdebug's
improved var_dump feature.
None of the native dump functions format the output for HTML rendering (as it
shouldn't!), which makes it difficult to read when you have a large/convoluted
object. For comparison:
var_export #
print_r #