Utilizing PHP’s print_r() function

This is just a quick tip, but ever since discovering it I use it constantly. A lot of developers use PHP’s print_r() function to display human-readable information about a variable, which makes it great for debugging arrays and objects (among other things) very quickly. However, you have to wrap the output in <pre></pre> tags otherwise it gets spit out in a jumbled mess and doesn’t display nicely.

echo '<pre>';
print_r($foo);
echo '</pre>';

That works just fine, but you can shorten it up by passing true to print_r()‘s second parameter, the $return flag, and mixing it in with your echo statements. What this does is tells print_r() to return the human-readable variable data instead of printing it to the screen right away.

echo '<pre>' . print_r($foo, true) . '</pre>';

Earth-shattering code breakthrough? Absolutely (not). However, it does turn three lines of code into one and makes it quicker (for me, anyway) to write quick debugging statements and move them around easier.

As an added bonus, you can “queue up” a bunch of print_r()‘s by capturing their output in a variable and then echo’ing it just once.

$debug = print_r($foo, true);
$debug .= print_r($bar, true);
echo '<pre>' . $debug . '</pre>';

Voila, shorter debugging statements that are easier to work with.

Tags:

  • Jack

    Good sharing, thanks.

  • http://www.hotmail.com eddy

    good, but not that much.

  • http://rstankov.com Radoslav Stankov

    Far better idea is to define your own function ( I call it ‘d’ :) ):

    function d(){
    echo ‘

    ';
        foreach(func_get_args() as $v){
           print_r($v);
        }
        echo '

    ‘;
    }

    And you can: d($a, $b, $c);

  • http://www.spicermatthews.com Spicer Matthews

    Wow. Sweet. Tip. I use print_r about 100 times a day. Always get annoyed. Particularly with Ajax returns. Tough to do a view source on an ajax return and see the print_r statement.

    Thanks.

  • AndyH

    For ajax, modify the above to log to a file and watch that with a separate bit of ajax, or tail -f instead

  • http://www.fastie.com Will Fastie

    Very useful tip – I learned something about print_r that I didn’t know. Thanks.

  • http://itech.hubpages.com/ Krrish

    “queue up” – Really New information for me…

  • Pingback: Building A PHP Database Connection Class From Scratch (using Singleton & ActiveRecord patterns) « CodeSlayer2010 : Slaying Code 24/7!

  • http://www.facebook.com/zaskarelli Elvis Zaskarelli

    One of the best tips I have come across this year! I got here via a search “print_r in ajax” so thanks very much!

  • http://www.facebook.com/tamas.kalman Tamas Kalman

    printf(‘<pre>%s</pre>’, print_r($variable, true));

  • Pingback: Building A PHP Database Connection Class From Scratch (using Singleton & ActiveRecord patterns) | Wow, I Didn't Know That!