Recursion ?

A

Anonymous

Guest
I come to web programming from an extensive background in client side C++ programming. Im used to recursion in alot of my previous programs and was wondering if PHP supports such a concept. I had tried a simple script and it didnt work as I anticipated. Take this for instance:
Code:
function display_tree($temp)
{
	if ( $temp < 10 )
	    	display_tree($temp+1);
	else
    		echo "display_tree($temp);\n<br>";
}

display_tree(0);

Now, in C++ that would have displayed that line 10 times decending to 0. I tried it in PHP and it only displays the one line ( the number 10 ). Am I going about this wrong or is this just not supported?

Thanks for the input.

Will
 
The function is working fine! You've set it to only output once the $temp is greater (or equal to) 10! Which is what it's done!

Try this:
Code:
function display_tree($temp) 
{ 
   if ( $temp < 10 ) {
          echo "display_tree($temp);\n<br>";
          display_tree($temp+1); 
} else {
          echo "display_tree($temp);\n<br>"; 
}
} 
display_tree(0);

Incidentally, that should output "display_tree(10);" if anything! If you want to print the value from a function, don't enclose it in quotation marks otherwise PHP will interpret it as a string! Use this method:
print display_tree($temp)."\n<br>";
 
Ah, I see what i was doing wrong. What i was over looking before was PHP returning to the point (basically going back to after the if statement ten times in my example) and continuing (sp?) on with the rest of the function. I edited the code to this:
Code:
function display_tree($temp)
{
	echo "Before checking and temp = $temp<br>";
	if ( $temp < 10 )
    		display_tree($temp+1);
	else
	    	echo "display_tree($temp);\n<br>";
	echo "After checking and temp = $temp<br>";
}

And got what I was looking for :) Thank you for the reply Jay.

Will
 
Back
Top