DEV Community

Cover image for Using dd (dump and die) function in PHP
Saymon Tavares
Saymon Tavares

Posted on

Using dd (dump and die) function in PHP

One of the most common ways to debug an error in PHP ecosystem is to dump the variable on the screen, and figure out what is going wrong with it.

The most common way we do it in PHP is via using var_dump function.

var_dump function dumps all the information about the variable or object on your page, but it does not stop the execution of the program further.

Letโ€™s consider an example where if you have an associate array and you want to dump it on the screen.

<?php

    $prices = [
        '๐Ÿ”' => 5.99,
        '๐ŸŸ' => 4,
        '๐Ÿป' => 10
    ];
    var_dump($prices);
Enter fullscreen mode Exit fullscreen mode

This is what you get on the screen.
screen
As you can see our code did not die and also the formatting very nice ๐Ÿค”

Using dd in PHP

If you are a laravel developer you must be aware of dd() function, dd dumps and die. There is no dd function in php if you try to do dd($prices) in the above example it will throw an error Call to undefined function dd().
We can however create our own dd function, that will dump the variable/object and then die the script execution.
We have created a new dd function, and wrapped the var_dump around pre tags so that it gives out a nice formatting in the browser and a more readable dump.

<?php

    function dd($data) {
        echo '<pre>';
        var_dump($data);
        echo '</pre>';
        die;
    }

    $prices = [
        '๐Ÿ”' => 100,
        '๐ŸŸ' => 10,
        '๐Ÿป' => 4
    ];
    dd($prices);
Enter fullscreen mode Exit fullscreen mode

This is how you see the output, and the php scripts die after dumping. It does not execute the further code.
result function
You can isolate this function in a reusable functions file or a Class.


I hope you enjoyed the read!

Feel free to follow me on GitHub, LinkedIn and DEV for more!

Top comments (1)

Collapse
 
he110 profile image
Elijah Zobenko • Edited

A very handy thing!
I would suggest two things:

  • You can extend the argument list to make it support an unlimited amount of data passed
// three dots before $additional are important
function dd($data, ...$additional): void
{
    echo '<pre>';
    var_dump($data, $additional);
    echo '</pre>';
    die;
}

dd('test', ['another' => 'test'], null, false, 123);
Enter fullscreen mode Exit fullscreen mode
  • There is an amazing library called var-dumper. It makes the similar thing, but supports cli mode