Problem solving when PHP recursively returns a value

  • 2020-05-30 19:30:09
  • OfStack

We have all sorts of problems with PHP recursion, but one of the more vexing is the problem with the return value of PHP recursion. Actually, if you think about it, it's a very simple question. But that simple question bothered me for half the afternoon. The problem is the return value of the recursive function.

This is the beginning:


<?php   
function test($i)   
{   
$i -= 4;   
if($i < 3)   
{   
return $i;   
}   
else    
{   
test($i);   
}   
}   
echo test(30);   
?> 

This code looks fine, but there is something wrong with else. The test executed here does not return a value. So even though it's $i < At 3, the entire return $i function still does not return a value. The above PHP recursive return value function is modified as follows:

< ?php   
function test($i)   
{   
$i -= 4;   
if($i < 3)   
{   
return $i;   
}   
else    
{   
return test($i); // increase return,  Let the function return a value    
}   
}   
echo test(30);   
?>

The code example above is a concrete solution to the problem with the recursive return value of PHP.


Related articles: