SoFunction
Updated on 2025-03-02

Three common ways of PHP recursion

Recursion: The function calls its own programming method, similar to a loop, so there must be a termination condition in the function called recursively, otherwise it will become a dead loop

Infinite level: In fact, it is not the real infinite level, it is just that the level is uncertain, so we call it the infinite level

Because recursion is commonly used to implement infinite-level classification, we are used to bringing classification when infinite-level.

Three common techniques for recursion:

Static variables, global variables, references

1. Static variable method

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

2. Global variable method

$i = 0;
function loopGlobal(){
  global $i;
 echo $i.' ';
 $i++;
 if($i<10){
    loopGlobal();
 }
}
loopGlobal();//Output 0 1 2 3 4 5 6 7 8 9 

3. Quote and pass parameters

function loopReference(&$i=0){
 echo $i.' ';
 $i++;
 if($i<10){
  loopReference($i);
 }
}
loopReference();//Output 0 1 2 3 4 5 6 7 8 9 

Recursion is often used to deal with infinite-level problems. By combining the above three methods and using them in actual conditions, flexible use can solve your own infinite-level problems. If you are new to me, I would love to see your confusion in the comments.

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support. If you want to know more about it, please see the following links