Home  >  Article  >  Backend Development  >  How to implement string flip function in PHP

How to implement string flip function in PHP

小云云
小云云Original
2017-12-07 16:30:562067browse

When it comes to the method of achieving string reversal, everyone will think of using a loop. Indeed, looping is a small memory footprint and simple to implement. But there is another way to achieve such a function, and that is recursion.

PHP supports recursive functions, which are functions that call themselves. These functions are particularly useful for dynamically browsing data structures such as joined lists and trees.

Example:

<?php 
//递归实现字符串翻转
function reverse_r($str){
  if(strlen($str)>0){
    reverse_r(substr($str,1));
  }
  echo substr($str,0,1);
  return;
}
//循环实现字符串翻转
function reverse_i($str){
  for($i=1; $i<=strlen($str);$i++){
    echo substr($str,-$i,1);
  }
  return;
}
reverse_r("Hello");
reverse_i("everyone");
?>

result:

How to implement string flip function in PHP

Related recommendations:

How to implement string flipping in php (including Chinese)

Chinese and English string flipping Function_PHP tutorial

How to implement string flip in PHP

The above is the detailed content of How to implement string flip function in PHP. 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