This article can be found online:
http://www.netbulge.com/index.php?session=0&action=read&click=open&article=1146307390
Echo is commonly used to output the content of variables to the screen, but a lot of people are not aware that it accepts several parameters and prints them all out. For example, the following is an acceptable use of echo:
$str1='PHP program output';
$str2=' for debugging';
echo $str1, $str2;
Note: Since echo is a language construct it doesn't need parenthesis and will not allow them when being called with multiple arguments.
I often see a lot of messy code opening and closing the strings, like this:
echo $str1, ', ', $str2, ', ', $str3;
When it can be done in one chunk using double quotes:
echo "\n $str1, $str2 \n $str3 \n";
Notice that I added line returns to that string on top of the commas separating the values. As HTML output, those line returns would be lost unless you enclose the call in <pre> </pre> tags.
But in my opinion, the most useful tool to send output for debugging is the print_r() function. It will receive normal variables as well as arrays - including multidimensional arrays - and print all in a format easy to digest for the human reader:
$vars[]='PHP program output';
$vars[]='for debugging';
echo '<pre>';
print_r($vars);
echo '</pre>';
RESULT:
Array
(
[0] => PHP program output
[1] => for debugging
)
Now, this can get very useful very fast. Notice that the result of the print_r() function includes not only the values of the elements of the array but also their keys. One great way to take advantage of this is using the array keys to store other valuable information, such as the description of the element. For instance, the following complex loop could easily turn into a painful debugging session, but the value-tracking code makes a huge difference:
$k=100;
$vars['total']=0;
for ($j=10; $j<=$k; $j=($j*2)+1){
$vars['total']++;
$vars['entering loop #' . $vars['total']]=$vars['total'];
$vars['j at #' . $vars['total']]=$j;
$vars['k at #' . $vars['total']]=$k;
$k=($k*3/2) -$j; //The actual loop calculation
$vars['k after calc at #' . $vars['total']]=$k;
}
RESULT:
Array
(
[total] => 5
[entering loop #1] => 1
[j at #1] => 10
[k at #1] => 100
[k after calc at #1] => 140
[entering loop #2] => 2
[j at #2] => 21
[k at #2] => 140
[k after calc at #2] => 189
[entering loop #3] => 3
[j at #3] => 43
[k at #3] => 189
[k after calc at #3] => 240.5
[entering loop #4] => 4
[j at #4] => 87
[k at #4] => 240.5
[k after calc at #4] => 273.75
[entering loop #5] => 5
[j at #5] => 175
[k at #5] => 273.75
[k after calc at #5] => 235.625
)
In this case, adding six lines of variable-storing to a loop produces a well detailed play-by-play summary of the execution.