[PHP] Improving var_dump Readability by Adding Color and Line Breaks

crear var_dump


This article aims to address the issue of the often hard-to-read output of the frequently used PHP var_dump function by enhancing its readability through the addition of color and line breaks.





Goal of this article

When working with PHP, we often use var_dump to inspect variable contents.
However, the default var_dump output can be challenging to read. After getting accustomed to frameworks like Laravel, using var_dump in a raw PHP project can be disheartening.

While enclosing it in <pre> tags improves readability, we sought to make it even more readable by adding color and open-close buttons for easy expansion and collapse.

We tried to make the appearance as close to Laravel’s dump function as possible.




Code

 So firstly, here is the code (function) to drastically improve the readability of var_dump.
While it may be a bit lengthy, placing it in a common file will undoubtedly facilitate debugging!

function dump($s) {
    // Store the result of var_dump in a variable.
    ob_start();
    var_dump($s);
    $s = ob_get_contents();
    ob_end_clean();
    
    $s = preg_replace('/=>\s+/', '<span class=orange> => </span>', $s);                         // Add color to the arrow (orange)
    $s = preg_replace('/NULL/', '<span class=orange>null</span>', $s);                          // Add color to the null (orange)
    $s = preg_replace('/int\((\d+)\)/', '<span class=blue>$1</span>', $s);                      // Remove the type notation for INT and add color to the values (blue)
    $s = preg_replace('/bool\((.*)\)/', '<span class=orange>$1</span>', $s);                    // Remove the type notation for BOOL and add color to the values (orange)
    $s = preg_replace('/string\(\d+\) (".*")/', '<span class=green>$1</span>', $s);             // Remove the type notation for STRING and add color to the values (green)
    $s = preg_replace('/(array)\((\d+)\)/', '<span class=blue>$1:$2</span>', $s);               // Add color to the type notation of ARRAY (blue)
    $s = preg_replace('/object(.*)(#\d+) \(\d+\)/', '<span class=blue>object$1$2</span>', $s);  // Add color to the type notation of OBJECT (blue)
    $s = preg_replace('/\["(.*?)":.*protected\]/', '<span class=orange>#</span>$1', $s);        // Remove square brackets and notation for PROTECTED
    $s = preg_replace('/\["(.*?)":.*private\]/', '<span class=orange>-</span>$1', $s);          // Remove square brackets and notation for PRIVATE
    $s = preg_replace('/\["(.*?)"\]/', '<span class=orange>+</span>$1', $s);                    // Remove square brackets for PUBLIC
    $s = preg_replace('/\[(\d+)\]/', '<span class=blue>$1</span>', $s);                         // Remove square brackets around array index
    $s = preg_replace('/\"/', '<span class=orange>"</span>', $s);                               // Add color to double quotation marks (orange)

    // Add open-close operation
    while(preg_match('/\{/', $s)){
        $s = preg_replace('/\{([^{}]*)\}/','[<span class="toggle-button gray" onclick=this.classList.toggle("open")>▶</span><span class="toggle-content">$1</span>]', $s);
    }

    echo "
        <pre class='dump'>$s</pre>
        <script>
            // Set the top-level toggle button to the open state
            document.querySelectorAll('.dump').forEach((elem) => {
                elem.querySelector('.toggle-button')?.classList.add('open')
            })
        </script>
        <style>
            .dump {
                background-color: #212121;
                color: #fff;
                padding: 10px;
                overflow-x: auto;
                font-size: 12px;
                font-family: monospace;
            }
            .dump .toggle-button {
                cursor: pointer;
                font-size: 13px;
            }
            .dump .toggle-button.open {
                transform: rotate(90deg);
                display: inline-block;
            }
            .dump .toggle-button:not(.open) + .toggle-content {
                display: none!important;
            }
            .dump .blue { color: #42A5F5; }
            .dump .gray { color: #BDBDBD; }
            .dump .green { color: #8BC34A; }
            .dump .orange { color: #FFA726; }
        </style>
    ";
}






Comparison of readability

Let’s compare the output of an instance of the sample class using both the custom dump function from earlier and the regular var_dump for readability.

class SampleClass{
    public $hoge1 = true;
    public $hoge2 = false;
    public $hoge3 = null;
    private $foo1 = 'aaaaaaaa';
    private $foo2 = 1000000000;
    protected $fuga1 = [
        'aaa',
        'bbb',
        'ccc',
    ];
    protected $fuga2 = [
        'key1' => 'xxx',
        'key2' => 'yyy',
        'key3' => 'zzz',
    ];
}


result of var_dump

object(SampleClass)#1 (7) { [“hoge1”]=> bool(true) [“hoge2”]=> bool(false) [“hoge3”]=> NULL [“foo1″:”SampleClass”:private]=> string(8) “aaaaaaaa” [“foo2″:”SampleClass”:private]=> int(1000000000) [“fuga1”:protected]=> array(3) { [0]=> string(3) “aaa” [1]=> string(3) “bbb” [2]=> string(3) “ccc” } [“fuga2”:protected]=> array(3) { [“key1”]=> string(3) “xxx” [“key2”]=> string(3) “yyy” [“key3”]=> string(3) “zzz” } }

result of dump
object(SampleClass)#1 [
  +hoge1 => true
  +hoge2 => false
  +hoge3 => null
  -foo1 => "aaaaaaaa"
  -foo2 => 1000000000
  #fuga1 => array:3 [
    0 => "aaa"
    1 => "bbb"
    2 => "ccc"
  ]
  #fuga2 => array:3 [
    +key1 => "xxx"
    +key2 => "yyy"
    +key3 => "zzz"
  ]
]




It’s incredibly easy to read!

The arrays come with open-close buttons, allowing you to view only the parts you want to check. When outputting an object, symbols (+,-,#) are added to the left of the properties, indicating the access modifiers.
( + : public), ( – : private), ( # : protected)





Output & Execution End

It’s common to use exit after var_dump when you want to stop the process midway.
Along with the dump function from earlier, it’s convenient to have a function that handles output to execution end.

function dd($s){
    dump($s);
    exit;
}







That is all, it was about how to improve var_dump readability by applying Color and Line Breaks
Wishing you a great debugging life!

Sponsored Link

You can subscribe by SNS

Sponcerd Link

Leave a Reply

*