Unless you have special powers, debugging PHP can be a right pain in the arse.

We all use a selection of functions to help debug out PHP, whether it be to check function inputs and outputs, or the result of a calculation. Some of the functions I use are echo, print_r and debug_backtrace, I suspect you may have used some of these too.

These functions are great, but usually require additional code to make them work as we want them. You might want to append <br /> on the end of an echo or wrap a print_r with the <pre> tags.

Having to constantly add code to these functions is very time consuming and adds inconsistency, so here are a few functions that should help you with your future debugging.

The echo alternative

debug_e simply appends a <br /> to the end of an echo statement, saving time whilst separating your debugs line by line.

PHP Code:
function debug_e($message='') {
    echo(
$message."<br />");
}

// usage
debug_e($_POST['email']); 
The print_r alternative

This function will allow you to display the contents of arrays and objects by wrapping the output in <pre> tags, you can also specify a title to make finding the right output much quicker.

PHP Code:
function debug_r($arr,$title='') {
    if(
$title=='') {
        echo(
"<h1>debug_r</h1>");
    } else {
        echo(
"<h1>debug_r - ".$title."</h1>");
    }
    echo(
"<pre>".print_r($arr,true)."</pre>");
}

// usage
debug_r($_POST); 
The debug_backtrace alternative

PHP Manual for debug_backtrace()

debug_backtrace is a function that I have only recently discovered, it comes in particularly handy as I am working on a very large MVC based project. debug_backtrace provides an array (a massive one at that) that shows you the path your script has taken from the starting point to the point where you placed the function. The issue is the array is very complex, so this function simplifies it by outputting, line by line each file that has been used and on what line it executed the next function.

PHP Code:
function debug_trace($title='') {
    if(
$title=='') {
        echo(
"<h1>debug_trace</h1>");
    } else {
        echo(
"<h1>debug_trace - ".$title."</h1>");
    }
    foreach(
debug_backtrace() as $key=>$value) {
        if(isset(
$value['file']) && isset($value['line'])) {
            echo(
'Trace "'.$value['file'].'" on line '.$value['line'].'<br />');
        }
    }
    echo(
"<br /><br />");
}

// usage
debug_trace(); 
These debug functions will operate independently as they don't depend on one another, so feel free to use them all, or and desired selection.

I hope these help you improve your debugging efficiency, be sure to tell me how you get on with them.

ILMV