Three basic ways to implement recursion in PHP _php tips

Source: Internet
Author: User

Recursive functions are commonly used in a class of functions, the most basic feature is that the function itself calls itself, but must be in front of the call itself conditional judgment, otherwise unlimited unlimited call down. What can be done to implement recursive functions? This article lists three basic methods. Understand the basic knowledge of the water products, including the global variables, references, static variables, also need to understand their scope of action. Recursive functions are also a good technique for solving infinite-level classification. If you are interested in an infinite class, refer to PHP to implement an infinite class of classification using recursive functions. I am accustomed to use popular words to explain the complex truth, you really do not understand see the manual.

Use references to make arguments

Regardless of the reference does not make parameters, you must first understand what is the reference? A reference simply refers to a variable of two different names pointing to the same storage address. Each variable has its own storage address, and the assignment deletes each row of its own path. Now, two variables share a storage address. $a =& $b;. In fact, it is $a to share a room with $b regardless of their original storage address. Thus any change to the value of the stored address will affect both values.

Functions are also the same as each other, even with the same name. Recursive function is to consider the reference as a parameter, to become a bridge, the formation of two functions between the data sharing. Although the two functions appear to operate at different addresses, the actual operation is a 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 simple, with a<10 as a condition of judgment, the condition is established, then assigns a to result[]; passing the reference of result to the function will add the A to the result array of a per recursive output. Thus, this example generates an array of $result ([0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9).

This example is more interesting than the value of echo a. Believe that a lot of people think it is 12345678910, it is not, is 1098765432. Why, then? The function recursion is performed the next time before the function has been executed Echoa. The true execution of echo A is that when the a<10 condition is not satisfied, echo a returns result and, for the previous layer, executes the recursive function, starts the echo $a of this layer, and so on.

Take advantage of global variables

Using global variables to complete recursive functions, make sure you really understand what a global variable is. Global declares in a function that a variable is merely a reference to an external variable's name. The scope of the variable is still within the scope of this function. Changing the value of these variables, the value of the external variable with the same name changes naturally. But once used, a variable of the same name is no longer a reference of the same name. Using global variables to realize recursive functions there is no need to understand such a deep layer, but also to maintain the original view of global variables can logically understand the recursive function.

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

Using static variables

We often see static in the class, and today we use it in recursive functions. Remember the role of static: to initialize a variable only the first time it is called, and to preserve the value of the variable.

Give me a chestnut:

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

$count + +;
}
Test ();
Test ();
Test ();
Test ();
Test ();

What is the execution result of this piece of code? Is it 00000? Certainly not. Is 01234. First call test (), static $count initialization, after each execution will retain the $count value, no longer initialize, equivalent to ignoring the static $count = 0; This sentence.

So it is conceivable to apply static to the function of recursion. The variables that need to be used as "bridges" between recursive functions are initialized with static, and each recursion retains the value of the bridge variable.

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

Summarize

The so-called recursive function, the emphasis is how to handle the function call itself is how to ensure that the desired results can be reasonably "passed" between functions, of course, there is no need to pass between functions worthy of recursive functions, such as:

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

    Test ($a);
  }


In the face of such a function, we do not have to worry about the big headache. By the way, an in-depth understanding of variable reference knowledge is of great benefit in solving such problems.

Finally to share a PHP implementation of recursive and infinite classification method, the implementation of the following methods:

<?php
echo "<pre>";
$area = Array (
' id ' =>1, ' area ' => ' Beijing ', ' pid ' =>0 '),
array (' ID ' =>2, ' area ' => ' Guangxi ', ' pid ' = >0),
array (' ID ' =>3, ' area ' => ' Guangdong ', ' pid ' =>0),
array (' ID ' =>4, ' area ' => ' Fujian ', ' pid ' =>0),
Array (' ID ' =>11, ' area ' => ' Chaoyang District ', ' pid ' =>1 '),
array (' ID ' =>12, ' area ' => ' Haidian ', ' pid ' =>1),
Array (' ID ' =>21, ' area ' => ' Nanning ', ' pid ' =>2),
array (' ID ' =>45, ' area ' => ' Fuzhou ', ' pid ' =>4),
Array (' ID ' =>113, ' area ' => ' Asian Games Village ', ' pid ' =>11 '),
array (' ID ' =>115, ' area ' => ' Olympic Village ', ' pid ' =>11 ),
array (' ID ' =>234, ' area ' => ' wuming ', ' pid ' =>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 ']. " <br/> ";
Here the output is to see the effect
$list [] = $v;
T ($arr, $v [' id '], $lev + 1);
}
return $list;
}
$list = t ($area);
echo " 
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.