Considerations for using return in php recursive functions

  • 2020-12-19 20:56:21
  • OfStack

When using php recursion function, it is difficult to return the desired value correctly. If you do not understand the reason, it is difficult to find the error. Let's illustrate 1 with the following specific examples:
 
function test($i){ 
$i-=4; 
if($i<3){ 
return $i; 
}else{ 
test($i); 
} 
} 
echotest(30); 

This code doesn't look like a problem, you wouldn't think it was a problem if you didn't run 1, you wouldn't know if it was a problem if you ran it in time, but there's something wrong with else. The result executed in this code has no return value. So even though the condition is $i < At 3 return $i the whole function will not return a value. Therefore, the above PHP recursive function can be modified as follows (for more PHP tutorials, please visit the code home) :
 
function test($i){ 
$i-=4; 
if($i<3){ 
return $i; 
}else{ 
return test($i);// increase return, Let the function return a value  
} 
} 
echotest(30); 

Related articles: