Home  >  Article  >  Backend Development  >  How to reverse output string in PHP? Use recursive call output

How to reverse output string in PHP? Use recursive call output

青灯夜游
青灯夜游Original
2018-11-19 11:30:543903browse

How to reverse output string in PHP? This article will introduce to you how PHP uses recursive calls to reversely output strings. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

First of all, let’s understand what is a recursive call?

Recursive call: A function calls itself or calls itself again after calling other functions. To put it simply: it calls itself. Recursive calling is a solution and a logical idea, which can divide a large job into gradually smaller tasks.

Let's introduce

How PHP uses recursive calls to reversely output a string?.

Code example:


<?php 
header("content-type:text/html;charset=utf-8");
// 反向输出字符串
//使用递归的字符串

// 通过反向输出的字符串
function reverse($str) 
{ 
	if (($str == null) || 
		(strlen($str) <= 1)) 
	echo ($str); 

	else
	{ 
		echo ($str[strlen($str) - 1]); 
		reverse(substr($str, 0, 
			(strlen($str) - 1))); 
	} 
} 

// 程序代码
$str = "hello"; 
echo ($str);
echo ("\n反向输出:\n");
reverse($str); 

?>

Running result:


How to reverse output string in PHP? Use recursive call output

Description: Recursive function reverse() Reverse inputs the string as a pointer (str) and calls itself at the next position, passing the pointer (str 1). The recursion continues in this way and when the pointer reaches '\0', all the functions accumulated in the stack at the passed position (str) will be returned and outputted one after another.

Summary: The above is the entire introduction of this article on using recursive calls to reverse output strings in PHP. I hope it will be helpful to everyone's learning. For more related video tutorials, you can visit:

php tutorial!

The above is the detailed content of How to reverse output string in PHP? Use recursive call output. 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