Home  >  Article  >  Backend Development  >  Simple method to implement recursion in PHP

Simple method to implement recursion in PHP

小云云
小云云Original
2018-02-27 13:13:211646browse


//递归//斐波那契数列function digui($n){    if($n>2){        $arr[$n]=digui($n-1)+digui($n-2);        return $arr[$n];    }else{        return 1;    }
}//使用echo digui(5);

Summary:

First of all, you should think of what the exit is and put the exit in the else condition

For example, this For example, in the Fibonacci sequence, the exit is that the first two numbers are 1, that is, the elements with array subscripts 0 and 1 are 1 (exit)

Then find the pattern of the sequence. In this example, the pattern The latter number is the sum of the first two numbers, so the condition is $arr[$n]=digui($n-1)+digui($n-2)

Note: The rule must be the same as The function itself is related. In this way, the function itself calls itself. After the exit condition is met, the function loop ends

Note: Fibonacci sequence 1,1,2,3,5,8,13, 21,34....

The above is the detailed content of Simple method to implement recursion 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