Using Laravel’s 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 = array( 'Tires'=>100, 'Oil'=>10, 'Spark Plugs'=>4 );

var_dump($prices);

echo "<br><br>I am here";

This is what you get on the screen.

 

As you can see our code did not die and also the formatting isn;t 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.

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

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($variable){
    echo '<pre>';
    die(var_dump($variable));
    echo '</pre>';
}

$prices = array( 'Tires'=>100, 'Oil'=>10, 'Spark Plugs'=>4 );

dd($prices);

echo "<br><br>I am here";

This is how you see the output, and the php scripts die after dumping. It does not execute the further code.

You can isolate this function in a reusable functions file or a Class.

tgugnani: Web Stuff Enthusiast.