SoFunction
Updated on 2025-03-02

Three implementation methods of php recursive function and how to implement number accumulation

Recursive functions are a relatively common type of functions in programming. Their characteristics are that the function itself can call itself, but there must be conditional judgment before calling itself, otherwise it will cause infinite calls. This article lists three recursive function implementation methods. The first is to use references as parameters, the second is to use global variables, and the third is to use static variables. Understanding such problems requires some basic basics, including understanding of global variables, references, and static variables, and also to have some understanding of their scope of action. I won’t talk nonsense anymore. Please see the details below.

The first method: 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;. Actually, it means $a Regardless of your original storage address, you must $b Shared a room. 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.

Copy the codeThe code is as follows:

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 answer,a<10As a judgment condition, if the condition is true, a is assigned to result[]; passing the reference to result into the function, a generated by each recursion will be added to the result array result. Therefore, this example generates$resultThe array isArray ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 ) 。

What's more interesting about this example isecho a value. I believe many people think it is12345678910Well, it's not, it's1098765432. Why? Because the function performs the next function recursion before echo a is executed.

Real executionecho aYesa<10When the conditions are not met,echo a,returnresult,For the previous layer, after executing the recursive function, start executing theecho $a,And so on.

The second method: use global variables

Use global variables to complete recursive functions, make sure you really understand what global variables are。globalDeclare the variable within the function to be nothing more than a reference to the same name of the external variable. 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 used&, variables with the same name are no longer references 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.

Copy the codeThe code is as follows:

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

The third method: use static variables

We often see it in the classstatic,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:

Copy the codeThe code is as follows:

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

What is the execution result of this code? yes00000Is it? It must not be. yes01234. First calltest(),staticright$count Initialize, and it will be retained after each execution $count The value of the value is no longer initialized, which is equivalent to being directly ignoredstatic $count=0; This sentence.

Therefore, it is conceivable to apply static to recursive functions. Use variables that need to be used as "bridges" between recursive functionsstaticInitialize, every recursion will be preserved"Bridge variable"value.

Copy the codeThe code is as follows:

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

 

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:

Copy the codeThe code is as follows:

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

        test($a);
    }
}

The following is a piece of code to demonstrate the method of php using recursive functions to achieve numerical accumulation.

The code looks like this:

Copy the codeThe code is as follows:

<?php
function summation ($count) {
   if ($count != 0) :
     return $count + summation($count-1);
   endif;
}
$sum = summation(10);
print "Summation = $sum";
?>

When facing php recursive functions, there is no need to worry about it. In-depth understanding of variable reference related knowledge is very helpful for solving such problems. The above content is all about the three implementation methods of php recursive functions and how to achieve numerical accumulation. I hope it will be helpful to everyone's future learning.