Question

Every decent PHP programmer has a print_r or var_dump wrapper they use, love and assign shortcut keys to, why don't we share our favourite ones.

Was it helpful?

Solution

A full year of time and labor after asking this, I've finally open sourced my version of var_dump, Kint. Read about it in the project page, or directly in github.

Here's a screenshot:

kint

Sorry for the plug :)


EDIT: I'd just like to remind the commenters, that this is not a support forum, if you're having problems/want a feature, please file an issue. Support requesting comments will be flagged for deletion.

OTHER TIPS

My prefered on is the var_dump function, as provided by the Xdebug extension : just install the extension (easy, both on windows and Linux), and var_dump gets a better output :

  • better formating
    • HTML
    • colors
  • and you have options to tune how much informations should be displayed

And a quick screenshot :

xdebug


And, of course, Xdebug brings loads of other usefull stuff, like remote debugging (i.e. graphical debugging of your PHP application, in Eclipse PDT for instance), profiling, ...

I wrote my own: REF (demo):

r() output

Plans are to add text-only rendering, and display info about the input expression like Kint does...

Here's mine, which I use inline, very useful:

$pretty = function($v='',$c="&nbsp;&nbsp;&nbsp;&nbsp;",$in=-1,$k=null)use(&$pretty){$r='';if(in_array(gettype($v),array('object','array'))){$r.=($in!=-1?str_repeat($c,$in):'').(is_null($k)?'':"$k: ").'<br>';foreach($v as $sk=>$vl){$r.=$pretty($vl,$c,$in+1,$sk).'<br>';}}else{$r.=($in!=-1?str_repeat($c,$in):'').(is_null($k)?'':"$k: ").(is_null($v)?'&lt;NULL&gt;':"<strong>$v</strong>");}return$r;};

echo $pretty($some_variable);

You are looking for Krumo (Warning, Chrome alerts for Malware).

To put it simply, Krumo is a replacement for print_r() and var_dump(). By definition Krumo is a debugging tool (initially for PHP4/PHP5, now for PHP5 only), which displays structured information about any PHP variable.

I love Firephp plus firebug

  • It writes the logging information out using headers, so it doesn't break AJAX.
  • Gives you a very nice graphical representation of the variables/objects you log
  • Can display file name and line number where each log statement occurs
  • Easy to use in your project, either with a procedural or object-oriented API

I've been using dBug, which emulates Coldfusion's awesome cfdump tag:

http://dbug.ospinto.com/examples.php

My (partial) solution for this is the simply add a function like this (using Google Chrome):

<?
function console_dump($value)
{ 
?>
<script>
    console.log(<? echo json_encode($value); ?>);
</script>
<?
}
?>

Press Ctrl + Shift + J (opens up the console), and you can find there the JSON structure. Even more useful for a pretty print of JSON responses ofcourse.

A complete example of what I use ...

<pre>

<?php


//*********** Set up some sample data

$obj = new stdClass;
$obj->a=123;
$obj->pl=44;
$obj->l=array(31,32);

$options = array(
  'Orchestra'=>array(1=>'Strings', 8=>'Brass', 9=>$obj, 3=>'Woodwind', 16=>'Percussion'),
  2=>'Car',
  4=>'Bus',
  'TV'=>array(21=>'Only Fools', 215=>'Brass Eye', 23=>'Vic Bob',44=>null, 89=>false));


//*********** Define the function

function dump($data, $indent=0) {
  $retval = '';
  $prefix=\str_repeat(' |  ', $indent);
  if (\is_numeric($data)) $retval.= "Number: $data";
  elseif (\is_string($data)) $retval.= "String: '$data'";
  elseif (\is_null($data)) $retval.= "NULL";
  elseif ($data===true) $retval.= "TRUE";
  elseif ($data===false) $retval.= "FALSE";
  elseif (is_array($data)) {
    $retval.= "Array (".count($data).')';
    $indent++;
    foreach($data AS $key => $value) {
      $retval.= "\n$prefix [$key] = ";
      $retval.= dump($value, $indent);
    }
  }
  elseif (is_object($data)) {
    $retval.= "Object (".get_class($data).")";
    $indent++;
    foreach($data AS $key => $value) {
      $retval.= "\n$prefix $key -> ";
      $retval.= dump($value, $indent);
    }
  }
  return $retval;
}


//*********** Dump the data

echo dump($options);

?>
</pre>

Outputs ...

Array (4)
 [Orchestra] = Array (5)
 |   [1] = String: 'Strings'
 |   [8] = String: 'Brass'
 |   [9] = Object (stdClass)
 |   |   a -> Number: 123
 |   |   pl -> Number: 44
 |   |   l -> Array (2)
 |   |   |   [0] = Number: 31
 |   |   |   [1] = Number: 32
 |   [3] = String: 'Woodwind'
 |   [16] = String: 'Percussion'
 [2] = String: 'Car'
 [4] = String: 'Bus'
 [TV] = Array (5)
 |   [21] = String: 'Only Fools'
 |   [215] = String: 'Brass Eye'
 |   [23] = String: 'Vic Bob'
 |   [44] = NULL
 |   [89] = FALSE

Here is mine:

class sbwDebug
{
    public static function varToHtml($var = '', $key = '')
    {
        $type = gettype($var);
        $result = '';

        if (in_array($type, ['object', 'array'])) {
            $result .= '
        <table class="debug-table">
            <tr>
            <td class="debug-key-cell"><b>' . $key . '</b><br/>Type: ' . $type . '<br/>Length: ' . count($var) . '</td>
            <td class="debug-value-cell">';

            foreach ($var as $akey => $val) {
                $result .= sbwDebug::varToHtml($val, $akey);
            }
            $result .= '</td></tr></table>';
        } else {
            $result .= '<div class="debug-item"><span class="debug-label">' . $key . ' (' . $type . '): </span><span class="debug-value">' . $var . '</span></div>';
        }

        return $result;
    }
}

Styled with:

table.debug-table {
  padding: 0;
  margin: 0;
  font-family: arial,tahoma,helvetica,sans-serif;
  font-size: 11px;
}

td.debug-key-cell {
  vertical-align: top;
  padding: 3px;
  border: 1px solid #AAAAAA;
}

td.debug-value-cell {
  vertical-align: top;
  padding: 3px;
  border: 1px solid #AAAAAA;
}

div.debug-item {
  border-bottom: 1px dotted #AAAAAA;
}

span.debug-label {
  font-weight: bold;
}

I recently developed a free chrome extension (work in progress) in order to beautify my var dumps with no libraries, no pre tags and no installation to each and every app. All done with JavaScript and regEx. All you have to do is install the extension and your good to go. I am working on a Firefox version as well. Here is the GitHub page. I hope to have it available on the chrome and firefox webstores soon!

https://github.com/alexnaspo/var_dumpling

Here is an example output:

Example output

Tracy has a beautiful collapsable output using dump() function.

Those fancy libraries are great ... except the overhead. If you want a simple, pretty var_dump that takes infinite parameters, try my function. It adds some simple HTML. Data attributes are added too, if you use HTML5, lower versions will just ignore them, but makes it easy to open element in browser console and get a little more info if what you see on screen is not enough.

The layout is very simple, no overhead. Provides a ton of info for each parameter including things like gettype and even class name for Object dumps (including XML). It's tried and true, I've been using it for years.

function preDump() {    //  use string "noEcho" to just get a string return only
    $args = func_get_args();
    $doEcho = TRUE; $sb;
    if ($args) {
        $sb = '<div style="margin: 1em 0;"><fieldset style="display:inline-block;padding:0em 3em 1em 1em;"><legend><b>preDump: '.count($args).' Parameters Found.</b></legend>';
        foreach (func_get_args() as $arg) {
            if (gettype($arg) == 'string') if ($arg == 'noEcho') { $doEcho = FALSE; $sb = preg_replace('/(preDump: )[0-9]+/', 'preDump: '.(count($args)-1), $sb); continue; }
            $sb .= '<pre data-type="'.gettype($arg).'"';
            switch (gettype($arg)) {
                case "boolean":
                case "integer":
                    $sb .= ' data-dump="json_encode"><p style="border-bottom:1px solid;margin:0;padding:0 0 0 1em;"><b>gettype('.gettype($arg).')</b></p><p>';
                    $sb .= json_encode($arg);
                    break;
                case "string":
                    $sb .= ' data-dump="echo"><p style="border-bottom:1px solid;margin:0;padding:0 0 0 1em;"><b>gettype('.gettype($arg).')</b></p><p>';
                    $sb .= $arg;
                    break;
                default:
                    $sb .= ' data-dump="var_dump"';
                    if (is_object($arg)) $sb .= 'data-class="'.get_class($arg).'"';
                    $sb .= '><p style="border-bottom:1px solid;margin:0;padding:0 0 0 1em;"><b>gettype('.gettype($arg).')';
                    if (is_object($arg)) $sb .= ' ['.get_class($arg).']';
                    $sb .= '</b></p><p>';
                    ob_start();
                    var_dump($arg);
                    $sb .= ob_get_clean();
                    if (ob_get_length()) ob_end_clean();
            }
            $sb .= '</p></pre>';
        }
        $sb .= '</fieldset></div>';
    }
    else {
        $sb = '<div style="margin: 1em 0;"><fieldset style="display:inline-block;"><legend><b>preDump: [ERROR]</b></legend><h3>No Parameters Found</h3></fieldset></div>';
    }
    if ($doEcho) echo($sb);
    return $sb;
}

And If you use Codeigniter, add it too your CI EXTREMELY SIMPLY. First, go to application/config/autoload.php and make sure the helper 'string' is on.

$autoload['helper'] = array( 'string' ); 

Then simply go create a file named MY_string_helper.php in application/helpers and simple insert the function in a typical if statement for existence check.

<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
    if (!function_exists('preDump')) {
        function preDump() {
            ...
        }
    }
//  DON'T CLOSE PHP

|OR|, if you want to take it a different direction.

The following snippet is the same as above, except will show your variables in the browser console. This can sometimes make it easier to debug sql object calls and other array and object calls where you're missing the key name or whatever.

function consoleDump() {    //  use string "noEcho" to just get a string return only
    $args = func_get_args();
    $doEcho = TRUE; $sb;
    if ($args) {
        $sb = '<script type="text/javascript">console.log("<" + new Array('.(count($args) < 10 ? '49': '48').').join("-") + "[consoleDump: '.count($args).' items]" + new Array(50).join("-") + ">"); console.log([';

        foreach (func_get_args() as $i => $arg) {
            if (gettype($arg) == 'string') if ($arg == 'noEcho') { $doEcho = FALSE; $sb = preg_replace('/(consoleDump: )[0-9]+/', 'consoleDump: '.(count($args)-1), $sb); continue; }
            $sb .= '{ "type": "'.gettype($arg).'", ';
            switch (gettype($arg)) {
                case "boolean":
                case "integer":
                case "string":
                    $sb .= '"value": '.json_encode($arg);
                    break;
                default:
                    $sb .= '"value": '.json_encode($arg);
                    if (is_object($arg) || is_array($arg)) $sb .= ', "count": '.json_encode(count((array)$arg));
                    if (is_object($arg)) $sb .= ', "objectClass": "'.get_class($arg).'"';
            }
            $sb .= '}';
            if ($i < count($args)-1) $sb .= ', ';
        }
        $sb .= ']); console.log("<" + new Array(120).join("-") + ">"); </script>';
    }
    else {
        $sb = '<script type="text/javascript">console.log("<" + new Array(120).join("-") + ">");console.log("consoleDump: [ERROR] No Parameters Found");console.log("<" + new Array(120).join("-") + ">");</script>';
    }
    if ($doEcho) echo($sb);
    return $sb;
}

Works with everything!

consoleDump($simpXMLvar, $_SESSION, TRUE, NULL, array( 'one' => 'bob', 'two' => 'bill' ), (object)array( 'one' => 'bob', 'two' => 'bill' ));


<------------------------------------------------[consoleDump: 6 items]------------------------------------------------->
[Object, Object, Object, Object, Object, Object] 
// This drops down to show your variables in JS objects, like:
    0: Object
        count: 4
        objectClass: "SimpleXMLElement"
        type: "object"
        value: Object
        __proto__: Object
        // ...etc...
<-----------------------------------------------------------------------------------------------------------------------> 

To make the list more complete - Symfony developers released a usable-as-standalone dumper alternative:

https://github.com/symfony/var-dumper

You can read about it more here:

http://www.sitepoint.com/var_dump-introducing-symfony-vardumper/

I wrote small class that is similar to Krumo, but much easier to embed to app.

Here is link: https://github.com/langpavel/PhpSkelet/blob/master/Classes/Debug.php

And here sample output: http://langpavel.php5.cz/debug_sample.html

PHP Array Beautifier This simple tool takes an array or object output in PHP, such as a print_r() statement and formats it in color coding to easily read your data. http://phillihp.com/toolz/php-array-beautifier/

Yet another home-grown version:

http://github.com/perchten/neat_html

I like to think it's pretty flexible. It doesn't aim for particular output environment but has a bunch of optional arguments you can specify why change the output/print or behaviour, as well as some persistent settings.

Here is a chrome extension that I wrote to solve this problem.

https://chrome.google.com/webstore/detail/varmasterpiece/chfhddogiigmfpkcmgfpolalagdcamkl

I developed a chrome extension and jquery plugin in order to beautify var_dumps

https://github.com/netfox01/fleX-debug

My preferred is debug from https://github.com/hazardland/debug.php which is library with containing only single function named as debug (You can just copy that function in your project or in your library). Typical debug() html output looks like this:

enter image description here

But you can output data as a plain text with same function also (with 4 space indented tabs) like this (and even log it in file if needed):

string : "Test string"
boolean : true
integer : 17
float : 9.99
array (array)
    bob : "alice"
    1 : 5
    2 : 1.4
object (test2)
    another (test3)
        string1 : "3d level"
        string2 : "123"
        complicated (test4)
            enough : "Level 4"

If you're dealing with very big arrays in PHP, this function may help:

function recursive_print ($varname, $varval) {
  if (! is_array($varval)):
    print $varname . ' = ' . var_export($varval, true) . ";<br>\n";
  else:
    print $varname . " = array();<br>\n";
    foreach ($varval as $key => $val):
      recursive_print ($varname . "[" . var_export($key, true) . "]", $val);
    endforeach;
  endif;
}

It basically dumps the whole array where each element is in separate line, which is beneficial to find the right full paths for certain elements.

Example output:

$a = array();
$a[0] = 1;
$a[1] = 2;
$a[2] = array();
$a[2][0] = 'a';
$a[2][1] = 'b';
$a[2][2] = 'c';

See: How to export PHP array where each key-value pair is in separate line?

Mine , is a more simpler , for me I don't have a lot of knowledge/time to change infrastructure install xdebug , etc etc.

And in other cases, well you don't need much for a simple WP website for example

So I use:

highlight_string("\n<?" . var_export($var, true) . "?>\n");

that really help me a lot.

but because I prefer the DevConsole Environment I use this awesome but simple function:

https://codeinphp.github.io/post/outputting-php-to-browser-console/

Little tweak:

<?php 

/**
 * Logs messages/variables/data to browser console from within php
 *
 * @param $name: message to be shown for optional data/vars
 * @param $data: variable (scalar/mixed) arrays/objects, etc to be logged
 * @param $jsEval: whether to apply JS eval() to arrays/objects
 *
 * @return none
 * @author Sarfraz
 */
function logConsole($name, $data = NULL, $jsEval = FALSE)
{
     if (! $name) return false;

     $isevaled = false;
     $type = ($data || gettype($data)) ? 'Type: ' . gettype($data) : '';

     if ($jsEval && (is_array($data) || is_object($data)))
     {
          $data = 'eval(' . preg_replace('#[\s\r\n\t\0\x0B]+#', '', json_encode($data)) . ')';
          $isevaled = true;
     }
     else
     {
          $data = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
     }

     # sanitalize
     $data = $data ? $data : '';
     $search_array = array("#'#", '#""#', "#''#", "#\n#", "#\r\n#");
     $replace_array = array('"', '', '', '\\n', '\\n');
     $data = preg_replace($search_array,  $replace_array, $data);
     $data = ltrim(rtrim($data, '"'), '"');
     $data = $isevaled ? $data : ($data[0] === "'") ? $data : "'" . $data . "'";

$js = <<<JSCODE
\n<script>
// fallback - to deal with IE (or browsers that don't have console)
if (! window.console) console = {};
console.log = console.log || function(name, data){};
// end of fallback

console.log('===== PHP Dump =====');
console.log('$name');
console.log('$type');
console.log($data);
console.log('===== / PHP Dump =====');
console.log('\\n');
</script>
JSCODE;

     echo $js;
} # end logConsole

Another option is to

composer require symfony/var-dumper --save-dev

Then in your file you just use dump($var) and you'll end up with an output like so enter image description here

TVarDumper

This is a great tool which is intended to replace the buggy PHP function var_dump and print_r, since it can correctly identify the recursively referenced objects in a complex object structure. It also has a recursive depth control to avoid indefinite recursive display of some peculiar variables.

See: TVarDumper.php.


For other alternative solutions which provides more advantages over var_dump and print_r and can support circular references, please check: Using print_r and var_dump with circular reference.


For more ideas, check also: How do you debug PHP scripts?

I'm surprised nobody mentioned the easiest (albeit not very pretty) code. If you just want to get a readable output (no colors or indentation), a simple <pre> around a var_dump works, as in:

echo "<pre>";
var_dump($myvariable);
echo "</pre>";

Can't get much lower overhead than this!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top