Home » Development » PHP » Variable Dump – List

While trying to write a custom error handler, I came across a problem: PHP’s standard variable dump function (var_dump) does not output proper XHTML, so I wrote a function to do this.

<?php
function var_dump_list(&$var, $type = FALSE){
	if($type === FALSE) echo '<ul>'."\r\n";
 
	if(is_array($var)){
			if(count($var) > 0){
				echo (($type == FALSE) ? '<li style="list-style-type: none;">' : '').'array('.count($var).'){'."\r\n";
				echo '<ul>'."\r\n";
				foreach($var AS $k => $v){
					echo '<li style="list-style-type: none;">['.$k.'] =&gt; ';
					var_dump_list(&$v, TRUE);
				}
				echo '</ul>'."\r\n";
				echo '}</li>'."\r\n";
			}
			else echo '<li style="list-style-type: none;">array(0){ }</li>'."\r\n";
	}
	else if(gettype($var) == 'boolean') echo 'boolean &mdash; '.(($var) ? 'true' : 'false').'</li>'."\r\n"; 
	else echo gettype($var).' &mdash; '.$var.'</li>'."\r\n";
 
	if($type === FALSE) echo '</ul>'."\r\n";
}
?>

Usage:

<?php
$foo = array(1, 2, 3, array("4", 5));
$bar = array($foo, 6, 7E-10, false);
var_dump_list($bar);
?>

This will output:

array(4){
	[0] => array(4){
		[0] => integer — 1
		[1] => integer — 2
		[2] => integer — 3
		[3] => array(2){
			[0] => string — 4
			[1] => integer — 5
		}
	}
	[1] => integer — 6
	[2] => double — 7.0E-10
	[3] => boolean — false
}

Respond

You must be logged in to post a comment.