Do you know the precautions for using return in PHP recursive functions?

怪我咯
Release: 2023-03-12 19:40:01
Original
1333 people have browsed it

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);
Copy after login

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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!