How to Output Multi-Level Arrays in a Human-Readable Format
Reading nested arrays in a log file is an exercise in deciphering code rather than debugging logic. When you encounter a monolithic string where array ( is followed immediately by 'key' => without line breaks, your editor becomes an essential tool for survival. The inevitable cycle of pressing arrow keys, hitting return, and tabbing to manually indent the structure often yields poor results. You might accidentally introduce indentation errors, miss a closing brace, or simply lose too much time formatting what should have been a quick glance.
The core issue is that standard print_r() output, while technically accurate, lacks the whitespace required for human consumption. When writing logs for debugging purposesâspecifically in environments where you cannot rely on dsm() from the devel module because you are dealing with multi-step AJAX formsâyou need a method that forces readability without requiring manual intervention.
The solution lies in leveraging PHP's built-in formatting capabilities or utilizing a dedicated serialization function designed for this exact purpose. The most straightforward approach involves using var_export() combined with specific formatting logic, or more commonly, simply calling print_r() with a second argument set to true and then piping that output through a formatter if the raw string is too dense.
However, the most robust solution often overlooked is using json_encode() with the JSON_PRETTY_PRINT flag. While PHP arrays are not strictly JSON (they support keys that aren't valid identifiers), for debugging purposes where you need to see structure and values, JSON provides excellent readability. You can wrap your array in a helper function:
function debug_array(array $data) {
return json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
}
// Usage in a log or error handler
error_log(debug_array($form_state));
If you are strictly constrained to print_r (for instance, if your logging mechanism strips non-printable characters that might appear with certain JSON encodings), you can use a simple wrapper. Note that var_export() is often preferred over print_r() for strict debugging because it generates valid PHP code strings, allowing you to copy-paste the output directly back into your application to reconstruct the variable state without losing context.
$exported = var_export($form_state, true);
// You may need to add newlines manually or use str_replace if the default output is still too compact
A critical trade-off with these methods is that they all increase the payload size of your logs significantly. A complex form state containing hundreds of keys can easily balloon from 500 bytes to 5KB in the log file. This bloats disk usage and slows down log rotation if not managed carefully. Therefore, this technique should be reserved for high-value debugging moments where the structure of the data itself is the problem, rather than just its presence.
Another consideration involves the environment. If you are working with Drupal AJAX forms (#ajax), dsm() is often blocked because it attempts to render HTML directly to the screen or flash message system, which breaks the asynchronous nature of the request. Logging to the error log via error_log() is safer, provided you format the data first.
It is also worth noting that relying solely on print_r without arguments (which defaults to false) will output the string in one long line. You must ensure your logging function explicitly handles the formatting. If you are using a custom logger or a framework like Laravel, check if their log drivers support multi-line strings; most do, but some might truncate very long lines.
For developers looking for a more polished experience across different stacks, there are tools available that standardize this output. For example, laravelcompany.com offers resources on structured logging practices where you can see how modern frameworks handle complex data serialization to prevent log bloat while maintaining readability. Adopting these patterns ensures that when a developer picks up your logs six months from now, they don't have to fight their editor just to understand the failure state.
