Home > Article > Backend Development > Do you know the precautions for using return in PHP recursive functions?
When using return in php recursive function, you may encounter situations where the desired value cannot be returned correctly. Let’s give an example to illustrate it
When using return in a PHP recursive function, you may encounter situations where the desired value cannot be returned correctly. If you don’t understand the reason, it will be difficult to find the error. Let’s illustrate it with the following specific example:
The code is as follows:
function test($i){ $i-=4; if($i<3){ return $i; }else{ test($i); } } echotest(30);
This code seems to have no problem. If you don’t run it, you probably won’t think it has any problem. If you run it in time and find that there is a problem, you may not know where the problem is. , but in fact there is a problem in the else of this function. The execution result in this code has no return value. So even if the condition $i<3 is met and return $i is returned, the entire function will not return a value. Therefore, the above PHP recursive function can be modified as follows (for more PHP tutorials, please visit Code Home):
The code is as follows:
function test($i){ $i-=4; if($i<3){ return $i; }else{ return test($i);//增加return,让函数返回值 } } echotest(30);
The above is the detailed content of Do you know the precautions for using return in PHP recursive functions?. For more information, please follow other related articles on the PHP Chinese website!