PHPBuilder - Debug output of a variable



RSS Twitter
Snippets Other

Debug output of a variable

by: Rdiger Reinhardt
|
April 27, 2001

Version: 1.0

Type: Function

Category: Other

License: GNU General Public License

Description: These are two small functions which output variable type and content in a nice formatted way. Actually it uses var_dump(), but encloses the outtput in <hr>'s and uses a fixed-width font. Arrays are parsed recursively and every new instance is indented by a given number of &nbsp;'s. It only 'debugs' if a variable named $debug is set to 'true', so you can easily switch on or off the output globally.



//***********************************************************************************
// array_recurse & debug
// debug output a var
// by rdiger reinhardt  -  reinhardt@net-attach.de
//***********************************************************************************
function array_recurse($item, $spacer = " ")
{
	// increase spacer
	$var_sign = "<b><i><font color='#000080'>Array(" . sizeof($item) . ")</font></i></b>";
	if (strlen($spacer) != 1)
	{
		$spacer .= str_repeat("&nbsp;", strlen(key($item)) + 12);
	}
	else
	{
		$spacer = str_repeat("&nbsp;", strlen(strip_tags($var_sign)));
	}

	echo $var_sign . "<br>\n";

	// walk through the array...
	foreach($item as $key => $value)
	{
		// ...and start another recursion, if the value is an array again...
		if (is_array($value))
		{
        		echo $spacer;
			echo "[<font color='#CA0000'>$key</font>] => ";
			array_recurse($value, $spacer);
		}

		// ...or simply output the var.
		else
		{
			echo $spacer;
        		echo "[<font color='#CA0000'>$key</font>] => ";

                        // special handling for booleans...
        		if (gettype($value) == boolean)
        		{
        			$dsp_value = "false";
        			if ($value)
        			{
        				$dsp_value = "true";
        			}
        			echo "<font color='#408080'> bool(" . $dsp_value . ")</font>";
        		}
        		else
        		{
        			echo "<font color='#408080'>" . gettype($value) . " '" . $value . "'</font>";
        		}
        		echo "<br>\n";
		}
	}
	echo "<br>\n";
}

function debug($var, $dsp_text = "[debug output]")
{
	GLOBAL $debug;

	// debug mode set?
	if ($debug)
	{
		echo "<font face='courier new, courier' size='-1'>\n";
		echo "<hr size='1' noshade><b>$dsp_text: </b><br>\n";

		// if the var is an array, recurse...
		if (is_array($var))
		{
			array_recurse($var);
		}

		// ...or else dump the var.
		else
		{
			var_dump($var);
		}
		echo "<br><hr size='1' noshade>\n";
		echo "</font>\n";
	}
}

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
Rdiger Reinhardt

Comment:



Comment:

(Maximum characters: 1200). You have characters left.