Home  >  Article  >  Backend Development  >  How to solve the problem of return value in PHP recursive function

How to solve the problem of return value in PHP recursive function

黄舟
黄舟Original
2017-11-13 09:40:441858browse

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:

Analysis of three ways to implement php recursive functions


Examples of using php recursive functions

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!

Statement:
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