HTML and PHP Resources

Short easy to follow tutorials & more…

PHP Functions that Help You Debug

| 0 comments

Introduction

Writing code can be a daunting task filled with unexpected twist and turns even when we feel that we have everything planned out.

We will be covering some of the major functions in PHP that can be used for debugging our code, to track down unexpected execution and unexpected errors.  The functions we will focus on are:

  • echo()
  • print_r()
  • var_dump()
  • isset() 
  • empty()
  • exit() and die()

Printing Details to the Screen

PHP programming at its root is writing a set of instructions that are going to be parsed and executed. Although we may think that we know what is going to happen, we get unexpected results at times. To track down whats going wrong and where its going wrong we need to print extra statements to the screen so we can confirm that what we expect is happening is in actuality taking place.

Our old friend echo()

In a script that is giving us unexpected output, it is crucial that we trace our way through the script or through what we believe to be culprit, echo provides a basic means of doing so.

Using extra echoes into our scripts can help us confirm the existence of a variable and the value it holds.

For example, below we have taken a snippet of code and we have added echo statements at different points along the script with additional information for us comments. This helps us follow the logic of the script and the value of our selected variable at different points in the execution.

example_debug_echo.php :

PHP
1
2
3
4
5
6
7
8
9
10
11
<?php
$number = 1;
echo '<b>Starting:</b> '. $number .'<br>'; // Display our starting number
for($count = 2; $count <= 10; $count += 2)
{
echo 'Before:'. $number . '<br>'; // Display number before operation
$number *= $count;
echo 'After:'. $number . '<br><br>'; // Display number after operation
}
echo '<b>Ending:</b> '. $number; // Display our final number

This is an exaggerated example, but in reality we may have to do something like this in our scripts in order to track down where an error has occurred. Although this is a basic approach to debugging it can be an effective one.

Printing Arrays, Object and Additional Information Printing

The functions var_dump() and print_r() are used exclusively for debugging purposes. These two functions are identical in function but differ in the output that they display.

The print_r() function displays a variables contents in a readable format. This does not mean much for variables holding primitive data type like strings, integers and floating points, as they are simply printed to the screen, but arrays and objects get formatted into a string representation before they are printed to the screen.

The function var_dump() formats the value of its parameters into a readable form and displays information about the variables data type in addition to its value.

Here’s and example to show how both functions display the variables information in a more readable format in the case of strings and arrays.

example_print_r_var_dump.php :

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<pre>
<?php
$aString = "Hello Dolly";
$anArray = array('name' => 'Joel', 'age' => '20');
// A String
echo "A string and print_r():\n";
print_r($aString);
echo "\n\nA string and var_dump():\n";
var_dump($aString);
// An Array
echo "\n\nAn array and print_r():\n";
print_r($anArray);
echo "\n\nAn array and var_dump():\n";
var_dump($anArray);
?>
</pre>

Note that these functions are most useful when trying to debug arrays and objects. The visual structuring of the data makes it easier to read which arrays or properties are encased and by what names or keys they can be accessed. The var_dump() function is useful when confirming the type of data a variable holds, note in the example above, the ‘age‘ key of the ‘anArray’ variable holds a string of value 20, rather than an integer of value 20.

Is the Variable Ready

Next we have the functions isset() and empty(). These function simply establish whether a variable has been set or contains a value.

If you recall PHP is a loosely typed language and variables are allowed to contain any type of data. Variables do not need to be declared or instantiated before they are used, but in certain cases it is useful to know if a variable has been set or if it contains any value at all.

The isset() function tells us if a variable has been set by returning a boolean value of true or false.

In the following example we can see how we can check a variable to for whether or not it has been set.

example_isset.php :

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
/*
* Set the variable
* Then use isset to see if we have declared it
*/
$var1 = 'Some Value';
if(isset($var1))
echo 'Variable 1 is set! <br>';
else
echo 'Variable 1 is not set!<br>';
/*
* We have not declared $var2 anywhere
* Can you guess what the output will be?
*/
if(isset($var2))
echo 'Variable 2 is set! <br>';
else
echo 'Variable 2 is <b>not</b> set!<br>';

The empty() function tells us if a variable is empty,

In this modified example we can see that a set variables is considered empty if it contains the boolean equivalent of false or if the variable has not been set.

example_empty.php :

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php
/*
* set the variable and a value
* Then use empty to see if we have an empty value
*/
$var1 = 'Some Value';
if(empty($var1))
echo 'Variable 1 is empty! <br>';
else
echo 'Variable 1 is not empty!<br>';
// Change the value to an empty string
$var1 = '';
if(empty($var1))
echo 'Variable 1 is empty!(Contains an empty string) <br>';
else
echo 'Variable 1 is not empty!<br>';
/*
* We have not declared $var2 anywhere
* Can you guess what the output will be?
*/
if(empty($var2))
echo 'Variable 2 is empty! <br>';
else
echo 'Variable 2 is <b>not</b> empty!<br>';

Run it or Exit() or Die()

Lastly we have the constructs exit() and die(). These constructs terminate the script at the point they are used.

When using these constructs we can pass a string parameter that will be printed when the script exits.

example_exit_die.php :

PHP
1
2
3
4
5
6
7
<?php
$error = true;
if($error)
exit('An Error Occured. Unable to continue.'); // die() is equivalent
echo 'Welcome!';

Note that the last echo was not executed since the exit command was executed.

We can also use the or keyword as part of a statement with exit() and die() to determine if the script should continue. The left hand side of the or is interpreted as a boolean value, when the left hand side of the expression is false the right hand side gets executed.

example_or_exit_die.php :

PHP
1
2
3
4
5
6
7
8
<?php
$bar = "Hello";
$foo = isset($bar) or die('An Error Occured. $bar was not set.');
echo 'Welcome! $bar was set.';
/* Note we have not declared $tag*/
$fee = isset($tag) or die('An Error Occured. $tag was not set.');
echo 'Welcome! $tag was set.';

The example above checks whether a variable is set and the proceeds or exits the script. It is a short hand version of the if statement in the previous example.

The exit and die statements can be used when debugging a script and we want to stop execution at a certain point. Note that they are interchangeable.

Summary

Tracking down unexpected outcomes in our scripts simplifies to finding where were we have defined incorrect logic or an incorrect order of steps. Printing the type and value of variables is helpful in order to correct any errors in our script.

  • Printing useful information at different steps in your script with echo.
  • Confirm the key and value pairs in arrays and properties of object by using the print_r and var_dump functions.
  • Check whether a variable has been instantiated by using isset.
  • See if a variable contains an empty value or has not been set by using empty.
  • Its important to note that isset is not the same as empty
  • Stop execution of a script when arriving at a certain condition by using exit and die.

These functions are key to debugging or narrowing down problems in PHP scripts, although they can also become part of your script in order to handle errors appropriately.

Comments, Questions or Concerns

If you have any comments, questions or concerns feel free to voice them on this site or contact us directly at php@htmlandphp.com

Leave a Reply

Required fields are marked *.

*