How to create the debug (pr) function in WordPress by custom code?

While doing custom code in WordPress we have to investigate the code for the by and large we utilize the print_r and for the beautify we <pre></pre> use the tag in code. This can be time taking.

To resolve this problem we can create a common global function to print the value.

if(!function_exists('pr')) {
    function pr($p, $func="print_r",$r=false)    {
        if(!$func) $func='print_r';
        $bt = debug_backtrace();
        $caller = array_shift($bt);
        $file_line = "<strong>" . $caller['file'] . "(line " . $caller['line'] . ")</strong>\n";
        if(!$r)    { //if print
            echo '<pre>';
            print_r($file_line);
            $func($p);
            echo '</pre> ';
        } else { //if return
            ob_start();
            echo '<pre>';
            print_r($file_line);
            $func($p);
            echo '<pre>';
            $d = ob_get_contents();
            ob_end_clean();
            if(filter_var($r, FILTER_VALIDATE_EMAIL)) {
                $headers = 'From: [email protected]' . "\r\n" .
                'Reply-To: [email protected]' . "\r\n" .
                'X-Mailer: PHP/' . phpversion();
                mail($r, 'Debug Output', $d, $headers);
            }
            return $d;
        }
    }
}

Place the above code in you function.php file. To call the pr function call like below

<?php
    $cars = array(
        "Volvo",
        "BMW",
        "Toyota"
    );
    pr($cars);
?>