How to output (to a log) a multi-level array in a format that is human-readable?
Asked 07 September, 2021
Viewed 2.4K times
  • 64
Votes

I'm working on a drupal site and when debugging, I am always having to read through long, nested arrays. As a result, a large portion of my life is spent using the arrow, return, and tab keys, to split up 1000+ character strings into a nested, readable format.

For drupal devs, I can't use devel's dsm(), as I'm working with multi-step #ahah/#ajax forms, and I can only output the arrays to the error log, not to the screen.

Visual example:

Evil:

array ( 'form_wrapper' => array ( '#tree' => true, '#type' => 'fieldset', '#prefix' => '', '#suffix' => '', '#value' => '', 'name' => array ( '#type' => 'textfield', '#title' => NULL, '#size' => 60, '#maxlength' => 60, '#required' => false, '#description' => NULL, '#attributes' => array ( 'placeholder' => 'Email', ), '#post' => array ( 'form_wrapper' => array ( 'name' => '', 'pass' => '', ),
...

Good:

array ( 
'form_wrapper' => array ( 
    '#tree' => true, 
    '#type' => 'fieldset', 
    '#prefix' => '<div>', 
    '#suffix' => '</div>', 
    '#value' => '', 
    'name' => array ( 
        '#type' => 'textfield', 
        '#title' => NULL, 
        '#size' => 60, 
        '#maxlength' => 60, 
        '#required' => false, 
        '#description' => NULL, 
        '#attributes' => array ( 
            'placeholder' => 'Email', 
        ), 

Edit: Sorry, by "not output to screen", I meant via drupal's system messages where it's possible to output arrays in a clickable, nested format (using devel.module).

8 Answer