In our previous article, we introduced to you the use of php recursive functions and how to implement them. So what about the problem of return when we use php recursive functions? Today I will explain to you the problem of return values in PHP recursive functions!
The problem of returning values in recursive functions
/* 循环去除字符串左边的0 */ function removeLeftZero($str){ if($str['0'] == '0'){ $str = substr($str, '1'); removeLeftZero($str); }else{ return $str; } }
In most people's eyes, there is no problem with this code. If you don't run it, you don't know where the problem lies? After running like this, there will be no return value if it is recursive. Even if the else condition is met after recursion, there will be no return value. It should be changed to
/* 循环去除字符串左边的0 */ function removeLeftZero($str){ if($str['0'] == '0'){ $str = substr($str, '1'); return removeLeftZero($str); // 给函数增加返回值 }else{ return $str; } }
Summary:
I believe that through this article, everyone will have a new understanding of the return value problem that appears in PHP recursive functions, and also know how to solve it. I hope it will be helpful to you!
Related recommendations:
How to use php recursive functions effectively? Typical examples of php recursive functions
What are php recursive functions and simple examples to explain
The above is the detailed content of How to solve the problem of return value in PHP recursive function. For more information, please follow other related articles on the PHP Chinese website!