PHP method to implement string flip function [recursion and loop algorithm]

Source: Internet
Author: User

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:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.