SoFunction
Updated on 2025-03-02

Three basic ways to implement recursion in PHP

Recursive functions are a type of functions we often use. The most basic feature is that the function itself calls itself, but it must be judged conditionally before calling itself, otherwise it will continue to be called infinitely. What methods can be used to implement recursive functions? This article lists three basic methods. Understanding them originally requires a certain amount of basic knowledge, including understanding of global variables, citations, and static variables, and also understanding their scope of action. Recursive functions are also a good trick to solve infinite-level classification. If you are interested in infinite-level classification, please refer to PHP to use recursive functions to implement infinite-level classification. I am used to using popular words to explain complicated truths, and you really don’t understand, please refer to the manual.

Use references as parameters

Regardless of whether the reference is used as a parameter or not, you must first understand what the reference is? References simply refer to two variables with different names pointing to the same block of storage address. Originally, each variable has its own storage address, and the assignment and deletion are their own. Now, two variables share a storage address. $a=&$b; . In fact, it means that $a has to share a room with $b regardless of its original storage address. Therefore any change to the storage address value will affect both values.

Functions are originally different, even functions with the same name. Recursive functions consider taking references as parameters to become a bridge to form data sharing between two functions. Although the two functions seem to operate different addresses, they actually operate on the same memory address.

function test($a=0,&$result=array()){
$a++;
if ($a<10) {
 $result[]=$a;
 test($a,$result);
}
echo $a;
return $result;

}

The above example is very short. If a<10 is used as the judgment condition, if the condition is true, a is assigned to result[]; passing the reference to result into the function, a will be added to the result array result by each recursion. Therefore, the $result array generated in this example is Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 ).

What's more interesting in this example is the value of echo a. I believe many people think it is 12345678910, but in fact it is not, it is 1098765432. Why? Because the function performs the next function recursion before echoa is executed. The real execution of echo a is when the condition a < 10 is not met, echo a, returns result. For the previous layer, after executing the recursive function, start executing the echo $a of this layer, and so on.

Example 2.

PHP references allow two variables to point to the same content, for example $a = &$b; This means $a and $b point to the same variable.

As shown in the following example, because $data uses reference pass, the data will be accumulated all the time.

function recursion(&amp;$data = [], $i = 0)
{
  if ($i &lt; 10) {
    $data[] = $i;
    $i++;
    $this-&gt;recursion($data, $i);
  }
  return $data;
}
// Call$this-&gt;recursion();  // [0,1,2,3,4,5,6,7,8,9]

Utilize global variables

To complete recursive functions with global variables, make sure you do understand what a global variable is. global declares that a variable is nothing more than a reference to the same name of an external variable within the function. The scope of action of variables is still within the scope of this function. Change the values ​​of these variables, and the values ​​of external variables with the same name will naturally change. But once & is used, the variable with the same name is no longer a reference to the same name. There is no need to understand such a deep understanding of recursive functions using global variables. You can understand recursive functions naturally by maintaining your original view of global variables.

function test($a=0,$result=array()){
 global $result;
 $a++;
 if ($a<10) {
  $result[]=$a;
  test($a,$result);
 }
 return $result;
}

global declares that a variable is nothing more than a reference to the same name of an external variable within the function. The scope of action of variables is still within the scope of this function. Change the values ​​of these variables, and the values ​​of external variables with the same name will naturally change.

function recursion($data = [], $i = 0)
{
  global $data;
  if ($i &lt; 10) {
    $data[] = $i;
    $i++;
    $this-&gt;recursion($data, $i);
  }
  return $data;
}
 
// Call$this-&gt;recursion();  // [0,1,2,3,4,5,6,7,8,9]

Take advantage of static variables

We often see static in classes, and today we use it to recursive functions. Remember what static does: the variable is initialized only when the function is called for the first time, and the variable value is preserved.

Take a chestnut:

function test(){
static $count=0;
echo $count;

$count++;
}
test();
test();
test();
test();
test();

What is the execution result of this code? Is it 00,000? It must not be. It is 01234. First, test() is called for the first time, and static initializes $count. After that, the value of $count will be retained after each execution and will no longer be initialized, which is equivalent to directly ignoring the static $count=0; sentence.

Therefore, it is conceivable to apply static to recursive functions. Initialize variables that need to be "bridge" between recursive functions with static, the value of "bridge variable" will be retained every recursive.

function test($a=0){
 static $result=array();
 $a++;
 if ($a<10) {
  $result[]=$a;
  test($a);
 }
 return $result;
}

Static variables are only initialized on the first call. It only exists in the local function domain, but its value is not lost when the program execution leaves this scope.

function recursion($i = 0)
{
  static $data = [];
  if ($i &lt; 10) {
    $data[] = $i;
    $i++;
    $this-&gt;recursion($i);
  }
  return $data;
}
 
// Call$this-&gt;recursion();  // [0,1,2,3,4,5,6,7,8,9]

Summarize

The so-called recursive function focuses on how to handle the function call itself to ensure that the required results can be "passed" between functions. Of course, there are also recursive functions that do not need to be passed between functions, such as:

function test($a=0){
 $a++;
 if ($a<10) {
  echo $a;

  test($a);
 }
}

Facing such a function, we don’t have to worry about it. By the way, a deep understanding of variable citations is of great benefit to solving such problems.

Finally, I would like to share with you a php method to implement recursion and infinite classification. The specific implementation methods are as follows:

&lt;?php
echo "&lt;pre&gt;";
$area = array(
array('id'=&gt;1,'area'=&gt;'Beijing','pid'=&gt;0),
array('id'=&gt;2,'area'=&gt;'Guangxi','pid'=&gt;0),
array('id'=&gt;3,'area'=&gt;'Guangdong','pid'=&gt;0),
array('id'=&gt;4,'area'=&gt;'Fujian','pid'=&gt;0),
array('id'=&gt;11,'area'=&gt;'Chaoyang District','pid'=&gt;1),
array('id'=&gt;12,'area'=&gt;'Haidian District','pid'=&gt;1),
array('id'=&gt;21,'area'=&gt;'Nanning City','pid'=&gt;2),
array('id'=&gt;45,'area'=&gt;'Fuzhou City','pid'=&gt;4),
array('id'=&gt;113,'area'=&gt;'Asian Games Village','pid'=&gt;11),
array('id'=&gt;115,'area'=&gt;'Olympic village','pid'=&gt;11),
array('id'=&gt;234,'area'=&gt;'Wuming County','pid'=&gt;21)
);
function t($arr,$pid=0,$lev=0){
static $list = array();
foreach($arr as $v){
if($v['pid']==$pid){
echo str_repeat(" ",$lev).$v['area']."&lt;br /&gt;";
//The output here is to see the effect$list[] = $v;
t($arr,$v['id'],$lev+1);
}
}
return $list;
}
$list = t($area);
echo "&lt;hr &gt;";
print_r($list);
?&gt;

This is the end of this article about the three basic ways to implement recursion of php. For more related php recursion content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!