Helper Functions: Small Changes, Big Win

If your job is anything like mine, there is just never enough time to finish everything. When working on projects, I try to find ways which can speed up my development process. There are many tools and ideas which can help greatly in this area, however, sometimes very small behavioral changes can result in a cumulative win. When working on web-based projects in PHP, I often find that I need to see what’s contained in an array or an object so I can get my code just right. PHP offers a nice way to do this with the print_r() function, but there’s a problem in using it for web apps: It’s monospaced.

Now, this may seem like a miniscule problem, as you can easily wrap the print_r() in <pre></pre>, but that takes away keystrokes that would be better suited for other tasks. To get around this repetitive bloat, I normally declare a function in the global scope of my project. This function simply accepts the object you wish to print out, and wraps it in the HTML <pre></pre> tags to display the monospaced text as intended, The code snippet below outlines this task a little more clearly:

    function ap($var) 
    { 
        echo '<pre>'; 
        print_r($var); 
        echo '</pre>'; 
    }

Using print_r() alone:
Array ( [name] => Tim Garrison [favoriteFoods] => Array ( [0] => Blueberry Pie [1] => Pizza [2] => Tortelini ) )

Using this ap() function:

Array
(
    [name] => Tim Garrison
    [favoriteFoods] => Array
        (
            [0] => Blueberry Pie
            [1] => Pizza
            [2] => Tortelini
        )
 
)

By using this function, you simply issue a ap($foo); in your code, rather than having to spell out each bit of the HTML tag. This is just one example of how making a small change in how you code results in directing your efforts on actually writing code rather than formatting your debugging statements!