Home > Daily Programming > PHP Knowledge > PHP recursive algorithm (1)

PHP recursive algorithm (1)

藏色散人
Release: 2019-02-28 09:08:54
Original
13920 people have browsed it

In the previous article, we introduced to you the PHP algorithm series "PHP Random Picking Algorithm" and "PHP Bubble Sorting Algorithm 》, friends in need can learn about it. In this article, we will continue to bring you common PHP algorithms, namely PHP recursive algorithm.

PHP recursive algorithm (1)

#In the PHP development process, recursive algorithms are often used for infinite classification. So the so-called recursion is a mechanism in which a function calls itself. To put it simply, you call yourself directly or indirectly in the function body, but you need to set the conditions for self-calling. If the conditions are met, the function itself is called. If the conditions are not met, the self-calling of this function is terminated.

And there are many ways to implement recursive algorithms, such as through "static variables", "global variables", and "passing parameters by reference".

Below we will introduce to you one of the methods using specific code examples, which is the method of using static variables!

The code is as follows:

<?php
function call(){
    static $i = 0;
    echo $i . &#39;&#39;;
    $i++;
    if($i<10){
        call();
    }
}

call();
Copy after login

Output:

0 1 2 3 4 5 6 7 8 9
Copy after login

In this method, we mainly use static to define static variables to implement recursive sorting. As above, we have defined a call method and static variable $i. If we do not add a judgment to the $i variable but run it directly, an infinite loop will occur. So we added an if conditional judgment statement here. Finally, the loop calls its own method.

This article is an introduction to the use of static variables to implement PHP recursive algorithms. In subsequent articles, we will continue to introduce the relevant implementation methods of PHP recursive algorithms.

The above is the detailed content of PHP recursive algorithm (1). 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