
I often want to output an array for debugging purposes, but using var_dump() or print_r() on an array that includes true / false values and class objects can be problematic — false values appear empty, and class objects can include too much information. I wrote the following recursive static method (presented here as a function) to pre-filter an array for readability when using print_r() or var_dump().
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
function make_pretty_array( $mixed, $flatten = false ) { $ret = ''; if ( is_array( $mixed ) ) { foreach ( $mixed as $key => $val ) { $val = make_pretty_array( $val, $flatten ); // recurse for value if ( $flatten ) $ret .= $key.'='.$val.', '; else { if ( is_object( $mixed[$key] ) ) unset ( $mixed[$key] ); // dereference the value $mixed[$key] = $val; } } if ( $flatten ) $ret = '('.trim( $ret, ', ' ).')'; else $ret = $mixed; } elseif ( $mixed === false ) $ret = 'false'; elseif ( $mixed === true ) $ret = 'true'; elseif ( $mixed === null ) $ret = 'null'; elseif ( $mixed === '' ) $ret = '\'\''; elseif ( is_object( $mixed ) ) $ret = 'object '.get_class( $mixed ); else $ret = $mixed; return $ret; } |
The make_pretty_array() function above can return an array (default), or flatten the array into a single text string.
Example usage:
1 2 3 |
print_r( make_pretty_array( $array ) ); |
Example output:
1 2 3 4 5 6 7 8 9 10 11 |
Array ( [id] => 2504 [name] => post [is_post] => true [is_taxonomy] => false [is_user] => false [obj] => object WpssoProUtilPost ) |
1 2 3 |
(id=2504, name=post, obj=object WpssoProUtilPost, is_post=true, is_taxonomy=false, is_user=false) |