• Php tricks: print_r(); and how to make it work for you.

    Posted on November 18, 2010 by in Blog

    Chances are if you are a php developer, there will be a time when you will need to inspect a variable and its contents.  The best way I’ve found is to do so is through using the “print_r($variable)” command.

    However, you might find that print_r() lacks a certain luster.  Well, that luster is the wonders of “<pre>.”  If you are unfamiliar with the html element <pre></pre>, it is short for ‘Preformatted’ and simply means that any white-space formatting between the beginning and ending <pre> tags will be preserved when the browser outputs the text to screen..   This happens to be extremely valuable when examining an array, or an object, because of their multi-demensions.

    What I’ve done is created a new function, print_p(), which wraps print_r() with <pre> and </pre> for convenience.  Otherwise, if you want to see preformatted-text, you need to manually print”<pre>”; print_r(the variable); print “</pre>”;  which can be very time consuming if you frequently find yourself debugging..

    So, just place this somewhere in yours script, or wherever you feel necessary, but just think, print_p() can speed up your debugging.

    function print_p($var){
         print “<pre>”;
         print_r($var);
         print “</pre>”;
    }

    If you want to capture print_r()’s output in a variable, instead of printing it directly to the screen, you can pass true as the second parameter ie: $output = print_r($var, true);

    This way, you can include debug via the error_log($output) file, keep in mind that pre formatting will not work in the error_log.

    For further reading on the function-print_r() please visit php.net.

    Thanks,
    Dusty.

    Post Tagged with , ,

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.