Discussions of Drupal, Web Development, and Libraries

Basic PHP Code Troubleshooting Strategy

Well, I originally wrote this for a coworker, but thought that others might be interested in a simple strategy to use while investigating a problem during PHP coding, so here it is.

My basic process is the same process that Stephen Jones taught me long ago for narrowing down issues in code. You basically start at some point in your code and make sure things are right by echoing out the information that should be available at that point. If not, you back up and make sure earlier things are right. If they are right, you continue moving forward. You probably already know what I'm about to say, but I'll say it anyway. I'll use sort of an analogy involving a math problem.

Let's say that I have a long php script that involves an extensive multi-step process.

<?php
$x
= 0;
$x = $x + 3;
$x = $x + 3;
$x = $x + 3;
$x = $x + 3;
$x = $x + 3;
$x = $x + 3;
$x = $x + 3;
// $x should be 21 at this point.
echo "<p> x = ". $x ."</p>\n";
?>

If I have a problem in the end result... let's say that $x is coming out as 18 instead of 21.
I would start halfway down and see if $x is what I think it should be at that point. I'll throw in an echo statement to see.

<?php
$x
= 0;
$x = $x + 3;
$x = $x + 3;
$x = $x + 3;
echo
"<p> x = ". $x ."</p>\n";
$x = $x + 3;
$x = $x + 3;
$x = $x + 3;
$x = $x + 3;
// $x should be 21 at this point.
echo "<p> x = ". $x ."</p>\n";
?>

If it's 9 at that point, then the problem I'm looking for is located somewhere between the first echo statement and the second. Then I just continue moving the echo statement around until I find the source of my troubles.

If you need to print out the value of an array, you can use:

<?php
echo '<pre>';
print_r($array);
echo
'</pre>';
?>

...to see the contents of the array at any point.

Obviously this is a fairly simplistic example, but this strategy has pretty much always worked for me. It can be time consuming, but it's very effective. You're basically repeatedly asking "is X what I think it should be at this point in the code?"