A Simple Example of PHP Recursive Algorithm

  • 2021-11-29 23:13:00
  • OfStack

Recursive functions are self-calling functions, Call each other directly or directly in the function body, but it is necessary to set the conditions of self-calling. If the conditions are satisfied, the function itself will be called. If it is not satisfied, the self-calling of this function will be stopped, and then the main control right of the current process will be returned to the upper layer function to perform. Perhaps this explanation is still difficult to understand, for example


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

For example, the output after all is

2 1 0 < - > 0 1 2

Let me explain why the output is so

Step 1, perform test (2), echo 2, and then due to 2 > 0. Perform test (1), followed by echo 2 that has not been performed in time

Step 2, perform test (1), echo 1, and then due to 1 > 0, perform test (0), followed by echo 1 that has not been performed in time

Step 3: Perform test (0), echo 0, Perform test (0), echo 0, now 0 > The condition of 0 is not satisfactory, instead of performing test () function, echo "" is performed, and the following echo 0 is performed

At this moment, the function is no longer calling itself, and the main control right of the process is returned to the upper layer function to perform, that is, the final echo that has just been performed by the test () function before it can be output, and the first layer of 0 is 1, that is, the upper layer of output 1 1 is 2, that is, the output 2 2 has no mountain 1 layer, so the output content is 2 1 0 < - > 0 1 2

Summarize


Related articles: