| 
 Posted by Jon Slaughter on 05/04/07 01:57 
<blessblessbless@gmail.com> wrote in message  
news:1178239947.037795.248560@o5g2000hsb.googlegroups.com... 
> Hey all, 
> I am self taught in PHP and my method is just trial and error most of 
> the time, but when trying doe not help anymore I get frustrated... I'm 
> sure some of you know what I mean. 
> 
> My problem is with a recursive(referring back to itself) function I am 
> trying to write. 
> The function works well on its own, and it also works recursively as 
> many times as I want it to. 
> I am going to give you a lite version of the function because it 
> doesn't really matter what it does. 
> 
> global $counter; 
> $counter=0; 
> function recursion($value){ 
> $counter++; 
> if ($counter > 10){exit("Recursion exceeded limit!");} 
> 
> $newvalue= blabla something with $value 
> 
> if (condition applies){recursion($newvalue);} 
> return $newvalue; 
> $counter=0; 
> } 
> 
 
Your counter is not global. you are creating a new counter variable each  
recursive step that is local to the function. So the the first if statement  
never does anything. 
use global $counter inside the function 
 
 global $counter; 
 $counter=0; 
 
 function recursion($value){ 
 global $counter; 
 $counter++; 
 if ($counter > 10){exit("Recursion exceeded limit!");} 
 
 $newvalue= blabla something with $value 
 
 if (condition applies){recursion($newvalue);} 
 return $newvalue; 
 $counter=0; 
 } 
 
Your last line $counter=0 is also not doing anything. your returning so  
anything after that point isn't going to be called. Its also probably not a  
good idea to do that unless you know exactly what your doing. (in this case  
its ok because it doesn't ever get called but in some circumstances it could  
end up causing an infinite loop). 
 
Jon
 
  
Navigation:
[Reply to this message] 
 |