SoFunction
Updated on 2025-03-02

Simple example of PHP recursive algorithm

The recursive function is a self-call function, which is called directly or directly within the function body, but it is necessary to set the self-call conditions. If the conditions are satisfactory, the function itself is called. If it is not satisfied, the self-call of this function will be stopped, and then the master control of the current process will be returned to the previous function for performance. Perhaps it is still difficult to understand for us to explain this way. For example,

function test ($n){
  echo $n." ";
  if($n>0){
    test($n-1);
  }else{
    echo "";
  }
  echo $n." "
}
test(2)

For example, the final output is

2 1 0<–>0 1 2

Let me explain why the output is

The first step is to fulfill test(2), echo 2, and then because 2>0, perform test(1), and there is still echo 2 that has not had time to fulfill.

The second step is to fulfill test(1), echo 1, and then because 1>0, perform test(0), there are still echo 1 that has not been able to fulfill it later.

The third step is to fulfill test(0), echo 0, fulfill test(0), echo 0, the condition of 0>0 is not satisfactory at this moment, and the test() function is not fulfilled, but echo "", and the subsequent echo 0 is fulfilled

At this moment, the function no longer calls itself. It starts to hand over the master control of the process to the previous layer function for execution, that is, to start performing the final echo that the test() function has not had time to output. The first layer of 0 is 1, that is, the previous layer of 1 is 2, that is, the output 2, 2, there is no mountain layer, so the output content is 2 1 0<->0 1 2

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