What is recursion in PHP? What are the ways to achieve this?

王林
Release: 2023-04-07 19:28:02
Original
3074 people have browsed it

What is recursion in PHP? What are the ways to achieve this?

What is recursion

Recursion: A programming method in which a function calls itself, similar to a loop, so the function called recursively must There is a termination condition, otherwise it will become an infinite loop.

Commonly used methods of recursion:

1. Static variable method

function loop(){
 static $i = 0;
 echo $i.' ';
 $i++;
 if($i<10){
     loop();
 }
}
loop();//输出 0 1 2 3 4 5 6 7 8 9
Copy after login

2. Global variable method

$i = 0;
function loopGlobal(){
  global $i;
 echo $i.&#39; &#39;;
 $i++;
 if($i<10){
    loopGlobal();
 }
}
loopGlobal();//输出 0 1 2 3 4 5 6 7 8 9
Copy after login

3. Reference parameter passing method

function loopReference(&$i=0){
 echo $i.&#39; &#39;;
 $i++;
 if($i<10){
  loopReference($i);
 }
}
loopReference();//输出 0 1 2 3 4 5 6 7 8 9
Copy after login

Recommended tutorial: PHP tutorial

The above is the detailed content of What is recursion in PHP? What are the ways to achieve this?. 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