PHP – Print a Prettier Array

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().

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:

print_r( make_pretty_array( $array ) );

Example output:

Array
(
    [id] => 2504
    [name] => post
    [is_post] => true
    [is_taxonomy] => false
    [is_user] => false
    [obj] => object WpssoProUtilPost
)
(id=2504, name=post, obj=object WpssoProUtilPost, is_post=true, is_taxonomy=false, is_user=false)
Find this content useful? Share it with your friends!