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

黄舟
Release: 2023-03-17 11:46:02
Original
1816 people have browsed it

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

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

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!

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!