Useful PHP functions to help you debug

There’s nothing like squashing a good bug. PHP offers some tools to help you along the way. One of those is print_r().

The function print_r() accepts two arguments.

print_r( $var, $return=false )

$var is the element you want to print or echo with your script. This is particularly useful with objects and arrays. Let’s say you have the array $var, and you run print_r($var). The output might look something like this:

Array ( [0] => "foo" [1] => "bar" [2] => Array ( [0] => Link ) )

The function will show you the contents of an array, including multidemensional arrays.

While this is good, print_r() doesn’t format the text well on it’s own. When you’re dealing with large objects and multidimensional arrays, seeing a large block of text can be quite confusing. It’s nice to wrap it in a <pre> tag to format it nicely. Additionally it’s useful to convert html symbols like < into a format that will show up in your output, e.g. &lt;, which will display as a less-than sign (<). I've been using the following function to help solve these problems:

function print_x($var, $decode = false){
    $return = print_r($var, true);
    if ($decode === true)
        $return = htmlspecialchars($return);
    $return = “<pre>{$return}</pre>”;
    echo $return;

Using print_x, you can get the same variable to display formatted, and with the html decoded:

    [a] => foo
    [b] => bar
            [0] => <a href='#'>Link</a>

Finally, when you can’t see a script running behind the scenes you need a way to create a log. There are other cases where print-ing or echo-ing your script can cause other errors such as cannot modify header information. In those situations, it’s not practical to output your debugging information. This is where saving to a file can be much more useful. Here’s a simple function to do that:

function print_v($info){
    $debug = print_r( $info, true );
    $base = "C:/wamp/www/debug.txt";
    $current = file_get_contents($file);
    $debug = $current . $debug . "\n\n";
    file_put_contents($file, $debug);

This function utilizes file_put_contents() to write the debug information to a file. This way the script can continue running uninterrupted. This example would be used on a local installation of wamp on Windows, but obviously $base can be set to output into any location you need.

A good example of when to use this is with cron jobs or mail scripts that are redirecting to confirmation messages without displaying text.

I hope you find these functions useful, they have certainly made things a lot easier for me.