Board index   FAQ   Search  
Register  Login
Board index php forum :: php coding PHP coding => General

Recursion ?

Ask about general coding issues or problems here.

Moderators: macek, egami, gesf

Recursion ?

Postby elitecodex » Mon Sep 09, 2002 5:28 pm

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: Select all
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
elitecodex
New php-forum User
New php-forum User
 
Posts: 68
Joined: Tue Jul 09, 2002 8:45 am
Location: East Coast, USA

Postby Jay » Tue Sep 10, 2002 1:55 am

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: Select all
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>";
Jay
 

Postby elitecodex » Tue Sep 10, 2002 3:33 am

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: Select all
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
elitecodex
New php-forum User
New php-forum User
 
Posts: 68
Joined: Tue Jul 09, 2002 8:45 am
Location: East Coast, USA


Return to PHP coding => General

Who is online

Users browsing this forum: Bing [Bot] and 3 guests

Sponsored by Sitebuilder Web hosting and Traduzioni Italiano Rumeno and antispam for cPanel.

cron