Working with any programming language will at some point throw a curve ball into the mix. Being able to debug PHP code is nearly a better skill than simply just coding way. Bugs and issues, amongst other things, will crop up in your codebase and you'll need the methods and logical thinking process to be able to find and fix that bug. Luckily PHP comes equipped with the necessary tools to help you debug such issues and for that, we can use PHP's var_dump function. Maybe you've got a syntax error or a PHP warning undefined array key error, and in order to fix it you need to view what the variables, objects, and array data are doing at certain points in the code, along with their scope, and what they contain. There are a few ways to do this either by using var_dump or print_r. Let's explore what they do, and how you can use them in your code.
What is var_dump in PHP?
The PHP function var_dump is a great variable handling function built directly into PHP that allows you to dump all information about a given variable. By "dump" we refer to displaying on-screen what's inside the provided variable for you to see. You may look at some code and think, that variable should contain X because it's doing Y, but sometimes that's not always the case, and that's where bugs can emerge. With var_dump you can pass all sorts of mixed values. Strings, ints, arrays, and objects, to name a few are things you can pass to it. It's important to note that var_dump does not return (void) anything it outputs directly as soon as called. This function takes the given parameters and displays them to the user in a structured way. One or more variables can be passed to this function, and it will display the type and value for each.
Take a look at the expected values and return of var_dump in the example below.
# Exptected values and return of var_dump
var_dump(mixed $value, mixed ...$values): void
Using PHP's var_dump on a string
Let's see what happens when you pass a string into the var_dump function and view its output. It could also be a variable that's of type string, but here we're passing a string directly.
var_dump('test 123');
# Will outputs
string(8) "test 123"
Using var_dump on an array
Arrays can also be examined because var_dump allows us to dump any type of scare type. Let's try an array and view data in a structured way.
$test = [1,2,3];
var_dump($test);
# Will output
array(2) {
[0]=> int(1)
[1]=> int(2)
}
Using var_dump on an object
Let's use PHP's 'stdclass' object, create an object, and a new property name, and assign it a value. Then let's var_dump show the object's data and view its information. The function will recursively search the whole object to show the structure, including all public, private, and protected properties of the object. Within a class, it is possible to control the debug information shown via the OOP magic method, __debugInfo(). If using __debugInfo be sure to set the function as public to avoid errors in PHP 8+.
$test = new stdClass();
$test->name = 'Test';
var_dump($test);
# Will output
object(stdClass)#1 (1) {
["name"] => string(4) "Test"
}
How var_dump can help us debug PHP code
The display of the type of variable you pass to var_dump is what really makes this function useful. Let's take the example below, we assign the variable 'int' with '1', thinking it's an integer when in fact, because we wrapped it in quotes, we've inadvertently typecasted it to a string. That means, if we inside an if statement, were to do a triple equals ("===") check on a variable, it would fail. It would fail because triple equals in PHP checks, the value, and the type match the given variable. Using var_dump to display this information, quickly tells us what the variable is, in PHP's eyes.
$int = '1';
var_dump($int);
# Outputs
string(1) "1"
# Because it's a string, this would fail
if ($int === 1) {
//...
}
# Therefore the statement should match a string
if ($int === '1') {
//...
}
Easily use var_dump on booleans and floats
Var_dump works with floats and booleans too. The below two examples pass a float of '1.59' and the bool 'true'.
var_dump(1.59);
# Outputs
float(1.59)
var_dump(true);
# Outputs
bool(true)
var_dump() vs print_r()
The print_r function in PHP is an alternative to using var_dump when it comes to debugging in PHP. The print_r functions differ slightly in terms of the data you get back when wanting information about a variable. First, var_dump displays the variable type, print_r does not, and secondly, you can tell print_r to return instead of direct output. That's particularly useful if you want to assign the data to a variable to use later on, maybe in a developer debug email. To tell print_r to return instead of output, set its second parameter as 'true'.
var_dump() vs error_log
When it comes to production-ready code, you never want var_dump to be callable. As var_dump outputs the information as soon as it gets called, this could lead to information exposure and instead, you should log this message away from the public, with PHP's error_log() function.
Xdebug's overloaded version of var_dump()
One thing to bear in mind is if you have the Xdebug module installed (a popular extension for PHP to aid PHP development) and are running with your version of PHP, it does limit the recursive search on array and object properties, to prevent computer memory exhaustion. It will tell you this structured data view and output the "*RECURSION*" string value. Here you know that at this particular point, xdebug stopped the recursive search on that object or array item. Another benefit of Xdebug is that the data that var_dump returns is overloaded by xdebug into colour syntax (pretty print) HTML output, to aid the developer with viewing its information. Another way to pretty print var_dump in PHP is by wrapping the output in HTML 'pre' tags. Using a 'pre' tag means the browser by default will apply formatting to the output so it's easier to read.
echo '<pre>';
var_dump($var);
echo '</pre>';
Conclusion
The var_dump function is a great debugging tool that you can use in your coding adventure. It will instantly help you solve problems with your code by showing you extact what is inside your PHP variables, arrays, and objects.
- If variable dumping objects or arrays are large in size because var_dump is recursive and dumps to your browser, be careful as it could exhaust your computer's memory usage (RAM).
- Use and install xdebug better developer experience when working on your localhost
- Use print_r instead of var_dump when dumping the information to the PHP error_log, with the return set to true