Troubleshooting with var_dump()

When code doesn't perform properly, checking that the variables contain what you expect is an important step in solving the problem. Was the value ever assigned to the variable? Does the variable still contain the value? Is the value formatted for the given the scenario? Let's look at some options for finding out.

Arrays and var_dump()

Most of the time, using a regular print or echo statement is sufficient for determining if a variable contains the desired value.

<?php
print $myVar;
?>

However, there are cases where this isn't enough. Displaying the contents of an array, for example, requires a little extra work. We could write a foreach loop to see what's in the array. Or…the same thing could be accomplished with one line of code:

<?php
$myArray = array('apple', 'pear', 'kazoo')
var_dump($myArray);
?>

The var_dump() function automatically outputs the array as follows:

array(3) {
     [0]=>
     string(5) "apple"
     [1]=>
     string(4) "pear"
     [2]=>
     string(5) "kazoo"
}

Note: the output appears without the line breaks in the browser. For an easier to scan version, go into the page's source code.

Checking the Variable Type

The var_dump() function also provides some extra insight on variables. For example, I had a PHP function which failed to execute since its argument needed to be a string or integer. I was trying to use the value calculated in the code below:

<?php
$thumbnails = array('thumb1.jpg', 'thumb2.jpg', 'thumb3.jpg', 'thumb4.jpg', 'thumb5.jpg');
$thumbPerColumn = ceil( count($thumbnails)/2 );
?>

The code figures out how many rows are needed to display the thumbnails in a two-column grid. Printing $thumbPerColumn showed that it contained "3"…so how is that not an integer? Well, using var_dump() shows that it's actually stored as a float.

<?php
var_dump($thumbPerColumn);  //output: float(3)
?>

Conclusion

Whether you're looking for a quick way to see the contents of an array or need to know more information about a variable, give var_dump() a whirl.

0 Comments

There are currently no comments.

Leave a Comment