Dump() Function - Formated print_r()

The print_r() is a very valuable function for all PHP developers. However, there is two problems with this function -

To solve these problems, I have created a function in PHP that will call the print_r() function. It will put the code generated by the print_r function inside <pre> tags. That will make the data readable from the browser.

If the given argument is not an array it will take the necessary action according to its data type. If the argument is an array, print_r() is used. If the argument is a object, var_dump() is used - with <pre> formatting. If it is anything else, it is printed with a var_dump().

I have crated a JavaScript port for the dump function, if you are intrested.

Sample Code

$data = array(
    'success'    =>    "Sweet",
    'failure'    =>    false,
    'array'      =>    array(),
    'numbers'    =>    array(1,2,3),
    'info'       =>    array(
                        'name'    =>    'Binny',
                        'site'    =>    'http://www.openjs.com/'
                 )
);

Result using print_r($data)

Array ( [success] => Sweet [failure] => [array] => Array ( ) [numbers] => Array ( [0] => 1 [1] => 2 [2] => 3 ) [info] => Array ( [name] => Binny [site] => http://www.openjs.com/ ) )

If you view the source of this document, the above output will make a lot more sense. But if you are looking at it in a browser, it is much more difficult to understand it.

Result using dump($data)

Called from : /home/binco/public_html/php/scripts/dump/index.php at line 54
-----------------------
Array
(
    [success] => Sweet
    [failure] => 
    [array] => Array
        (
        )

    [numbers] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [info] => Array
        (
            [name] => Binny
            [site] => http://www.openjs.com/
        )

)
-----------------------

dump(5);

Called from : /home/binco/public_html/php/scripts/dump/index.php at line 58
=========>int(5)
<=========

dump("Hello");

Called from : /home/binco/public_html/php/scripts/dump/index.php at line 62
=========>string(5) "Hello"
<=========

Code

<?php
/** Function : dump()
 * Arguments : $data - the variable that must be displayed
 * Prints a array, an object or a scalar variable in an easy to view format.
 */
function dump($data) {
    if(
is_array($data)) { //If the given variable is an array, print using the print_r function.
        
print "<pre>-----------------------\n";
        
print_r($data);
        print 
"-----------------------</pre>";
    } elseif (
is_object($data)) {
        print 
"<pre>==========================\n";
        
var_dump($data);
        print 
"===========================</pre>";
    } else {
        print 
"=========&gt; ";
        
var_dump($data);
        print 
" &lt;=========";
    }

Subscribe to Feed