PHP Debugging Followup - The dump function

Submitted by mikehostetler on Mon, 02/19/2007 - 12:24

I was in some old code this weekend and found another little PHP debugging gem. I had another version of a dump function that I used a long time ago, but stole this one from the Zend Framework because it was better. So, use this as a replacement for print_r() or var_dump().

Check out the function after the jump.

<?php
/**
* Stolen from the Zend Framework
* http://framework.zend.com/developer/browser/trunk/library/Zend.php
*/
function dump($var, $label=null, $echo=true)
{
   
// format the label
   
$label = ($label===null) ? '' : rtrim($label) . ' ';

   

// var_dump the variable into a buffer and keep the output
   
ob_start();
   
var_dump($var);
   
$output = ob_get_clean();

   

// neaten the newlines and indents
   
$output = preg_replace("/]\=\>\n(\s+)/m", "] => ", $output);
    if (
PHP_SAPI == 'cli') {
       
$output = PHP_EOL . $label
               
. PHP_EOL . $output
               
. PHP_EOL;
    } else {
       
$output = '<pre>'
               
. $label
               
. htmlentities($output, ENT_QUOTES)
                .
'</pre>';
    }

    if (

$echo) {
        echo(
$output);
    }
    return
$output;
}
?>
Blog Topics: