How to Make print_r Output Readable (Browser, Logs and CLI)
4 min read
You add print_r($data); to a page, reload, and get this:
Array ( [id] => 42 [name] => Alice [active] => 1 [deleted] => [manager] => [score] => 9 [roles] => Array ( [0] => admin [1] => editor ) )
Nothing is wrong with print_r. It printed perfectly formatted, indented output. The browser threw the formatting away, because HTML collapses newlines and runs of spaces into a single space. This post covers how to keep that structure intact wherever you're reading the output, and what to do once readable isn't enough.
1. In the browser: wrap it in <pre>
The <pre> element tells the browser to keep whitespace exactly as it is:
echo '<pre>' . htmlspecialchars(print_r($data, true)) . '</pre>';
Two details matter here:
print_r($data, true)returns the output as a string instead of printing it immediately, so you can wrap it.htmlspecialchars()escapes any HTML inside your values. Without it, a value like<b>Alice</b>gets rendered as bold text instead of shown literally, and a value containing<script>gets executed. That matters when you're dumping user input.
Now you get the real structure:
Array
(
[id] => 42
[name] => Alice
[active] => 1
[deleted] =>
[manager] =>
[score] => 9
[roles] => Array
(
[0] => admin
[1] => editor
)
)
No access to the code? Use View Source (Ctrl+U / Cmd+Option+U) instead of the rendered page. The source shows the raw response with every newline intact.
2. Make a tiny helper
If you dump things often, stop typing the <pre> boilerplate. A small helper that also behaves on the command line:
function pr(mixed $value, string $label = ''): void
{
$out = print_r($value, true);
if (PHP_SAPI === 'cli') {
echo ($label !== '' ? "{$label}:\n" : '') . $out . PHP_EOL;
return;
}
echo '<pre style="background:#f6f8fa;padding:12px;border-radius:6px;font-size:13px">';
if ($label !== '') {
echo '<strong>' . htmlspecialchars($label) . "</strong>\n";
}
echo htmlspecialchars($out) . '</pre>';
}
pr($order, 'order before save');
Put it in a dev-only include and keep it out of production code, so a forgotten pr() can't leak data to real users.
3. In log files: return mode is your friend
Often you can't print to the page at all: an API endpoint, an AJAX request, a queued job. Send the dump to a log instead:
error_log(print_r($data, true));
Where that ends up depends on your error_log ini setting. Usually it's the web server's error log or stderr. To keep debug output separate from real errors, write to your own file:
file_put_contents(
__DIR__ . '/debug.log',
date('c') . ' ' . print_r($data, true) . PHP_EOL,
FILE_APPEND | LOCK_EX
);
Framework shortcuts:
- WordPress: with
WP_DEBUGandWP_DEBUG_LOGenabled,error_log(print_r($data, true))lands inwp-content/debug.log. - Laravel:
logger(print_r($data, true));writes tostorage/logs/laravel.log. (Passing the array as context,Log::debug('order', $data), gives you JSON instead.)
Watch out for flattened logs. Some setups don't preserve multi-line messages. PHP-FPM worker output, Docker log drivers and log shippers may split each line into a separate entry, or escape newlines as a literal \n. If your dump arrives as one long line (or as dozens of unrelated-looking lines), that's why. Writing to your own file, as above, avoids the problem.
4. On the command line
In the CLI, print_r output is already formatted, because the terminal keeps whitespace. The problem there is length: a large dump scrolls straight past. Page it or search it:
php artisan tinker --execute 'print_r(App\Models\Order::first()->toArray());' | less
php debug.php | grep -n "email"
5. Know what print_r hides
Readable isn't the same as accurate. print_r converts every value to a string, so look at the output above again:
[active] => 1was the booleantrue.[deleted] =>wasfalse, and[manager] =>wasnull. They look identical.[score] => 9was the float9.0.
If you're debugging a condition (if ($user['deleted']), === null, empty()), switch to var_dump() for that value. We compare the three built-in dump functions in print_r vs var_dump vs var_export.
6. When the dump is thousands of lines long
Everything above makes a dump readable. That's not much help when it's a 4,000-line dump of a cart, its line items, their products and every product's attributes, and you need the one item whose sku is wrong.
That's the problem the PHP print_r Tree Viewer was built for. Paste the output and it becomes a collapsible tree:
- Already flattened? Paste it anyway. If you copied the one-line version from a browser or a log, the parser rebuilds the structure from the
(,)and[key] =>markers. - Collapse to a depth. Expand everything to depth 2 to see the overall shape, then open only the branch you care about.
- Search by key, value or both, with case-sensitive, whole-word and regex options. Matching nodes are highlighted and their parents opened, so you can see where in the structure each match lives.
- Copy the path to a node, like
Array → [items] → [12] → [sku], ready to turn into$cart['items'][12]['sku']. - Compare siblings. Click a key such as
[status]to see its value across every sibling record. That's the quickest way to spot the one order that'spendingwhen the rest arepaid. - Prettify re-indents messy multi-line output before you parse it.
Everything runs in your browser. Nothing you paste is uploaded, so it's safe for dumps that contain customer data or credentials.
Quick checklist
- Browser shows one long line → wrap in
<pre>withhtmlspecialchars(print_r($x, true)), or use View Source. - Can't print to the page →
error_log(print_r($x, true))or write to your own debug file. - Values look "empty" → check them with
var_dump; it might befalseornull. - Dump is too big to read → paste it into the tree viewer and search instead of scrolling.