PHP method to implement string flip function [recursion and loop algorithm]
This example describes how to implement the string flip function in PHP. We will share this with you for your reference. The details are as follows:
When talking about how to implement string inversion, everyone will think of a loop. Indeed, loop is a simple method with a small memory usage. However, there is another way to implement this function, that is, recursion.
Php supports recursive functions. recursive functions are called by functions themselves. These functions are especially suitable for Dynamic Browsing of data structures, such as connection lists and trees.
Example:
<? Php // recursively implement string flip function reverse_r ($ str) {if (strlen ($ str)> 0) {reverse_r (substr ($ str, 1 ));} echo substr ($ str, 0, 1); return;} // returns the string flip function reverse_ I ($ str) {for ($ I = 1; $ I <= strlen ($ str); $ I ++) {echo substr ($ str,-$ I, 1) ;}return ;} reverse_r ("Hello "); reverse_ I ("everyone");?>
Result: