110
votes

I'm fixing some PHP scripts and I'm missing ruby's pretty printer. i.e.

require 'pp'
arr = {:one => 1}
pp arr

will output {:one => 1}. This even works with fairly complex objects and makes digging into an unknown script much easier. Is there some way to duplicate this functionality in PHP?

31 Answers 31

158
votes

This is what I use to print my arrays:

<pre>
    <?php
        print_r($your_array);
    ?>
</pre>

The magic comes with the pre tag.

3
  • 3
    This is actually much better than var_dump because var_dump trims the result if it's a big array or a big string... Aug 1, 2014 at 11:39
  • 3
    a simplified version will be: echo "<pre>" . print_r($array, 1) . "</pre>";
    – diezsiete
    Dec 12, 2014 at 18:08
  • Don’t forget to escape the output of print_r: $formatted = print_r($array, true); print "<pre>" . htmlspecialchars($formatted, ENT_QUOTES, 'UTF-8', true) . "</pre>";
    – Glutexo
    Jul 14, 2015 at 6:20
101
votes

Both print_r() and var_dump() will output visual representations of objects within PHP.

$arr = array('one' => 1);
print_r($arr);
var_dump($arr);
6
  • 42
    If you install the XDebug extension, the var_dump becomes an even prettier printer. Jul 22, 2009 at 20:56
  • 105
    To make it look even nicer in a browser use: echo "<pre>"; print_r($arr); echo "</pre>";
    – Dom M.
    Jul 22, 2009 at 23:30
  • 13
    To Domenic's point just wrap it: function pr($array = null) { print "<pre><code>" . print_r($array) . "</code></pre>"; } Jul 23, 2009 at 0:53
  • 10
    @darren_n: print_r() automatically outputs and doesn't return anything (unless its second parameter is true), so you can't concatenate to another string. Use the following instead: function pr($var) { print '<pre>'; print_r($var); print '</pre>'; } Jul 23, 2009 at 13:55
  • 6
    @Domenic You will likely want to `echo '<pre>', htmlentities(print_r($arr, true)), '</pre>' instead, lending some credibility to Darren's suggestion as well (:
    – user212218
    Jun 7, 2011 at 15:34
21
votes

For simplicity, print_r() and var_dump() can't be beat. If you want something a little fancier or are dealing with large lists and/or deeply nested data, Krumo will make your life much easier - it provides you with a nicely formatted collapsing/expanding display.

0
21
votes

The best I found yet is this:

echo "<pre>";
print_r($arr);
echo "</pre>";

And if you want it more detailed:

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

Adding a <pre> HTML tag in a web development environment will respect the newlines \n of the print function correctly, without having to add some html <br>

0
19
votes

For PHP, you can easily take advantage of HTML and some simple recursive code to make a pretty representation of nested arrays and objects.

function pp($arr){
    $retStr = '<ul>';
    if (is_array($arr)){
        foreach ($arr as $key=>$val){
            if (is_array($val)){
                $retStr .= '<li>' . $key . ' => ' . pp($val) . '</li>';
            }else{
                $retStr .= '<li>' . $key . ' => ' . $val . '</li>';
            }
        }
    }
    $retStr .= '</ul>';
    return $retStr;
}

This will print the array as a list of nested HTML lists. HTML and your browser will take care of indenting and making it legible.

7
votes

How about print_r?

http://www.php.net/print_r

6
votes

Remember to set html_errors = on in php.ini to get pretty printing of var_dump() in combination with xdebug.

6
votes

Best way to do this is

echo "<pre>".print_r($array,true)."</pre>";

Example:

$array=array("foo"=>"999","bar"=>"888","poo"=>array("x"=>"111","y"=>"222","z"=>"333"));
echo "<pre>".print_r($array,true)."</pre>";

Result:

Array
(
    [foo] => 999
    [bar] => 888
    [poo] => Array
        (
            [x] => 111
            [y] => 222
            [z] => 333
        )
)

Read more about print_r.

About the second parameter of print_r "true" from the documentation:

When this parameter is set to TRUE, print_r() will return the information rather than print it.

1
  • Perfect solution to send output from php to web browser.
    – Evhz
    Apr 2, 2016 at 12:10
4
votes

This is a little function I use all the time its handy if you are debugging arrays. The title parameter gives you some debug info as what array you are printing. it also checks if you have supplied it with a valid array and lets you know if you didn't.

function print_array($title,$array){

        if(is_array($array)){

            echo $title."<br/>".
            "||---------------------------------||<br/>".
            "<pre>";
            print_r($array); 
            echo "</pre>".
            "END ".$title."<br/>".
            "||---------------------------------||<br/>";

        }else{
             echo $title." is not an array.";
        }
}

Basic usage:

//your array
$array = array('cat','dog','bird','mouse','fish','gerbil');
//usage
print_array("PETS", $array);

Results:

PETS
||---------------------------------||

Array
(
    [0] => cat
    [1] => dog
    [2] => bird
    [3] => mouse
    [4] => fish
    [5] => gerbil
)

END PETS
||---------------------------------||
1
  • why downvote? works well doesn't it? I'm not gonna cry about it just curious if i am doing something wrong. I'm self taught so please enlighten me.
    – Laurence
    Jan 5, 2012 at 23:48
3
votes
error_log(print_r($variable,true));

to send to syslog or eventlog for windows

3
votes

If you're doing more debugging, Xdebug is essential. By default it overrides var_dump() with it's own version which displays a lot more information than PHP's default var_dump().

There's also Zend_Debug.

2
  • 2
    Blarg. Xdebug's var dump sucks because it outputs HTML... Oh yeah, looks fantastic on a CLI test.
    – jason
    Jul 23, 2009 at 4:12
  • Xdebug uses different output for CLI these days. Dec 24, 2012 at 14:08
3
votes

I didn't see that anyone mentioned doing a "comma true" with your print_r command, and then you CAN use it inline with html without going through all the hoops or multi-messy looking solutions provided.

print "session: <br><pre>".print_r($_SESSION, true)."</pre><BR>";
1
  • Additionally, you should also do htmlspecialchars() around the print_r(), to protect against possibly stored XSS threats.
    – Christian
    Mar 30, 2015 at 11:52
2
votes

a one-liner that will give you the rough equivalent of "viewing source" to see array contents:

assumes php 4.3.0+:

echo nl2br(str_replace(' ', ' ', print_r($_SERVER, true)));

2
votes

This function works pretty well so long as you set header('Content-type: text/plain'); before outputting the return string

http://www.php.net/manual/en/function.json-encode.php#80339

<?php
// Pretty print some JSON
function json_format($json)
{
    $tab = "  ";
    $new_json = "";
    $indent_level = 0;
    $in_string = false;

    $json_obj = json_decode($json);

    if($json_obj === false)
        return false;

    $json = json_encode($json_obj);
    $len = strlen($json);

    for($c = 0; $c < $len; $c++)
    {
        $char = $json[$c];
        switch($char)
        {
            case '{':
            case '[':
                if(!$in_string)
                {
                    $new_json .= $char . "\n" . str_repeat($tab, $indent_level+1);
                    $indent_level++;
                }
                else
                {
                    $new_json .= $char;
                }
                break;
            case '}':
            case ']':
                if(!$in_string)
                {
                    $indent_level--;
                    $new_json .= "\n" . str_repeat($tab, $indent_level) . $char;
                }
                else
                {
                    $new_json .= $char;
                }
                break;
            case ',':
                if(!$in_string)
                {
                    $new_json .= ",\n" . str_repeat($tab, $indent_level);
                }
                else
                {
                    $new_json .= $char;
                }
                break;
            case ':':
                if(!$in_string)
                {
                    $new_json .= ": ";
                }
                else
                {
                    $new_json .= $char;
                }
                break;
            case '"':
                if($c > 0 && $json[$c-1] != '\\')
                {
                    $in_string = !$in_string;
                }
            default:
                $new_json .= $char;
                break;                   
        }
    }

    return $new_json;
}
?>
2
votes

If you want a nicer representation of any PHP variable (than just plain text), I suggest you try nice_r(); it prints out values plus relevant useful information (eg: properties and methods for objects). enter image description here Disclaimer: I wrote this myself.

2
votes

A nice colored output:

echo svar_dump(array("a","b"=>"2","c"=>array("d","e"=>array("f","g"))));

will looks like:

enter image description here

source:

<?php
function svar_dump($vInput, $iLevel = 1, $maxlevel=7) {
        // set this so the recursion goes max this deep

        $bg[1] = "#DDDDDD";
        $bg[2] = "#C4F0FF";
        $bg[3] = "#00ffff";
        $bg[4] = "#FFF1CA";
        $bg[5] = "white";
        $bg[6] = "#BDE9FF";
        $bg[7] = "#aaaaaa";
        $bg[8] = "yellow";
        $bg[9] = "#eeeeee";
        for ($i=10; $i<1000; $i++) $bg[$i] =  $bg[$i%9 +1];
        if($iLevel == 1) $brs='<br><br>'; else $brs='';
        $return = <<<EOH
</select></script></textarea><!--">'></select></script></textarea>--><noscript></noscript>{$brs}<table border='0' cellpadding='0' cellspacing='1' style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0'>
<tr style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0'>
<td align='left' bgcolor="{$bg[$iLevel]}" style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0;'>
EOH;

        if (is_int($vInput)) {
            $return .= gettype($vInput)." (<b style='color:black;font-size:9px'>".intval($vInput)."</b>) </td>";
        } else if (is_float($vInput)) {
            $return .= gettype($vInput)." (<b style='color:black;font-size:9px'>".doubleval($vInput)."</b>) </td>";
        } else if (is_string($vInput)) {
            $return .= "<pre style='color:black;font-size:9px;font-weight:bold;padding:0'>".gettype($vInput)."(" . strlen($vInput) . ") \"" . _my_html_special_chars($vInput). "\"</pre></td>"; #nl2br((_nbsp_replace,
        } else if (is_bool($vInput)) {
            $return .= gettype($vInput)."(<b style='color:black;font-size:9px'>" . ($vInput ? "true" : "false") . "</b>)</td>";
        } else if (is_array($vInput) or is_object($vInput)) {
            reset($vInput);
            $return .= gettype($vInput);
            if (is_object($vInput)) {
                $return .= " <b style='color:black;font-size:9px'>\"".get_class($vInput)."\"  Object of ".get_parent_class($vInput);
                if (get_parent_class($vInput)=="") $return.="stdClass";
                $return.="</b>";
                $vInput->class_methods="\n".implode(get_class_methods($vInput),"();\n");
            }
            $return .= " count = [<b>" . count($vInput) . "</b>] dimension = [<b style='color:black;font-size:9px'>{$iLevel}</b>]</td></tr>
            <tr><td style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0'>";
            $return .=  <<<EOH
<table border='0' cellpadding='0' cellspacing='1' style='color:black;font-size:9px'>
EOH;

            while (list($vKey, $vVal) = each($vInput)){
                $return .= "<tr><td align='left' bgcolor='".$bg[$iLevel]."' valign='top' style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0;width:20px'><b style='color:black;font-size:9px'>";
                $return .= (is_int($vKey)) ? "" : "\"";
                $return .= _nbsp_replace(_my_html_special_chars($vKey));
                $return .= (is_int($vKey)) ? "" : "\"";
                $return .= "</b></td><td bgcolor='".$bg[$iLevel]."' valign='top' style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0;width:20px;'>=></td>
                <td bgcolor='".$bg[$iLevel]."' style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0'><b style='color:black;font-size:9px'>";

                if ($iLevel>$maxlevel and is_array($vVal)) $return .=  svar_dump("array(".sizeof($vVal)."), but Recursion Level > $maxlevel!!", ($iLevel + 1), $maxlevel);
                else if ($iLevel>$maxlevel and is_object($vVal)) $return .=  svar_dump("Object, but Recursion Level > $maxlevel!!", ($iLevel + 1), $maxlevel);
                else $return .= svar_dump($vVal, ($iLevel + 1), $maxlevel) . "</b></td></tr>";
            }
            $return .= "</table>";
        } else {
            if (gettype($vInput)=="NULL") $return .="null";
            else $return .=gettype($vInput);
            if (($vInput)!="") $return .= " (<b style='color:black;font-size:9px'>".($vInput)."</b>) </td>";
        }
        $return .= "</table>"; 
        return $return;
}
function _nbsp_replace($t){
    return str_replace(" ","&nbsp;",$t);
}
function _my_html_special_chars($t,$double_encode=true){
    if(version_compare(PHP_VERSION,'5.3.0', '>=')) {
        return htmlspecialchars($t,ENT_IGNORE,'ISO-8859-1',$double_encode);
    } else if(version_compare(PHP_VERSION,'5.2.3', '>=')) {
        return htmlspecialchars($t,ENT_COMPAT,'ISO-8859-1',$double_encode);
    } else {
        return htmlspecialchars($t,ENT_COMPAT,'ISO-8859-1');
    }
}
1
vote

Since I found this via google searching for how to format json to make it more readable for troubleshooting.

ob_start() ;  print_r( $json ); $ob_out=ob_get_contents(); ob_end_clean(); echo "\$json".str_replace( '}', "}\n", $ob_out );
1
  • 1
    this can be greatly simplified using print_r($json,1)
    – SorcyCat
    Apr 29, 2011 at 16:59
1
vote

If your server objects to you changing headers (to plain text) after some have been sent, or if you don't want to change your code, just "view source" from your browser--your text editor (even notepad) will process new lines better than your browser, and will turn a jumbled mess:

Array ( [root] => 1 [sub1] => Array ( ) [sub2] => Array ( ) [sub3] => Array ( ) [sub4] => Array ( ) ...

into a properly tabbed representation:

[root] => 1
  [sub1] => Array
      (
      )

  [sub2] => Array
      (
      )

  [sub3] => Array
      (
      )

  [sub4] => Array
      (
      )...
1
vote

If you want to use the result in further functions, you can get a valid PHP expression as a string using var_export:

$something = array(1,2,3);
$some_string = var_export($something, true);

For a lot of the things people are doing in their questions, I'm hoping they've dedicated a function and aren't copy pasting the extra logging around. var_export achieves a similar output to var_dump in these situations.

1
vote

Here is a version of pp that works for objects as well as arrays (I also took out the commas):

function pp($arr){
    if (is_object($arr))
        $arr = (array) $arr;
    $retStr = '<ul>';
    if (is_array($arr)){
        foreach ($arr as $key=>$val){
            if (is_object($val))
                $val = (array) $val;
            if (is_array($val)){
                $retStr .= '<li>' . $key . ' => array(' . pp($val) . ')</li>';
            }else{
                $retStr .= '<li>' . $key . ' => ' . ($val == '' ? '""' : $val) . '</li>';
            }
        }
    }
    $retStr .= '</ul>';
    return $retStr;
}
1
vote

Here's another simple dump without all the overhead of print_r:

function pretty($arr, $level=0){
    $tabs = "";
    for($i=0;$i<$level; $i++){
        $tabs .= "    ";
    }
    foreach($arr as $key=>$val){
        if( is_array($val) ) {
            print ($tabs . $key . " : " . "\n");
            pretty($val, $level + 1);
        } else {
            if($val && $val !== 0){
                print ($tabs . $key . " : " . $val . "\n"); 
            }
        }
    }
}
// Example:
$item["A"] = array("a", "b", "c");
$item["B"] = array("a", "b", "c");
$item["C"] = array("a", "b", "c");

pretty($item);

// -------------
// yields
// -------------
// A : 
//     0 : a
//     1 : b
//     2 : c
// B : 
//     0 : a
//     1 : b
//     2 : c
// C : 
//     0 : a
//     1 : b
//     2 : c
0
votes

I think the best solution for pretty printing json in php is to change the header:

header('Content-type: text/javascript');

(if you do text/json many browsers will prompt a download... facebook does text/javascript for their graph protocol so it must not be too bad)

0
votes

FirePHP is a firefox plugin that print have a much pretty logging feature.

0
votes
    <?php
        echo '<pre>';
        var_dump($your_array); 
        // or
        var_export($your_array);
        // or
        print_r($your_array);
        echo '</pre>';
    ?>

Or Use external libraries like REF: https://github.com/digitalnature/php-ref

0
votes

Expanding on @stephen's answer, added a few very minor tweaks for display purposes.

function pp($arr){
    $retStr = '<ul>';
    if (is_array($arr)){
        foreach ($arr as $key=>$val){
            if (is_array($val)){
                $retStr .= '<li>' . $key . ' => array(' . pp($val) . '),</li>';
            }else{
                $retStr .= '<li>' . $key . ' => ' . ($val == '' ? '""' : $val) . ',</li>';
            }
        }
    }
    $retStr .= '</ul>';
    return $retStr;
}

Will format any multidimensional array like so:

enter image description here

0
votes

This is what i usally use:

$x= array(1,2,3);
echo "<pre>".var_export($x,1)."</pre>";
0
votes

I made this function to print an array for debugging:

    function print_a($arr) {
        print '<code><pre style="text-align:left; margin:10px;">'.print_r($arr, TRUE).'</pre></code>';
    }

Hope it helps, Tziuka S.

0
votes

How about a single standalone function named as debug from https://github.com/hazardland/debug.php.

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"
0
votes

In PHP 5.4 you can use JSON_PRETTY_PRINT if you are using the function json_encode.

json_encode(array('one', 'two', 'three'), JSON_PRETTY_PRINT);

http://php.net/manual/en/function.json-encode.php

-1
votes

I pulled a few of these options together into a wee little helper function at

http://github.com/perchten/neat_html/

You can print to html, neatly outputted, as well as jsonify the string, auto-print or return etc.

It handles file includes, objects, arrays, nulls vs false and the like.

There's also some globally accessible (but well scoped) helpers for when using settings in a more environment-like way

Plus dynamic, array-based or string optional arguments.

And, I keep adding to it. So it's supported :D

1
  • This would be a better answer if you included some code showing how it's used.
    – Teepeemm
    Jan 7, 2016 at 18:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.