How to implement recursive method in php

藏色散人
Release: 2023-03-17 08:34:01
Original
1191 people have browsed it

How to implement the php recursive method: 1. Implement it through static variables, code such as "function loop(){...}"; 2. Implement it through global variables, code such as "function loopGlobal() {...}"; 3. Implemented by passing parameters by reference, code such as "function loopReference(&$i=0){...}".

How to implement recursive method in php

The operating environment of this tutorial: Windows 7 system, PHP version 8.1, Dell G3 computer.

How to implement recursive method in php?

Three commonly used techniques for recursion:

Static variables, global variables, references

One 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

Three 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

Recursion is often used to deal with infinite problems. Through the above three methods combined with the actual situation, you can solve your own infinite problems by using them flexibly. question. If you're new to this, I'd love to hear your confusion in the comments.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to implement recursive method in php. 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