Three basic methods for php to implement Recursion

Source: Internet
Author: User
This article mainly introduces three basic methods for implementing recursion in php, including using reference as a parameter, using global variables, and using static variables to implement recursion. Relevant examples are attached, finally, we will give you a demonstration

This article mainly introduces three basic methods for implementing recursion in php, including using reference as a parameter, using global variables, and using static variables to implement recursion. Relevant examples are attached, finally, we will give you a demonstration

Recursive functions are commonly used. The most basic feature of a function is that the function itself calls itself, but it must be judged by conditions before it calls itself. Otherwise, it can be called infinitely. How can we implement recursive functions? This article lists three basic methods. Understanding it requires a certain amount of basic knowledge, including understanding global variables, references, and static variables. Recursive functions are also a good technique for solving infinite classification. If you are interested in unlimited classification, use the recursive function in php to implement unlimited classification. I use plain words to explain complex things. For more information, see the manual.

Using references as parameters

No matter whether the reference is done or not, you must first clarify what the reference is? A reference refers to two variables with different names pointing to the same storage address. Each variable has its own storage address, and values are assigned to and deleted separately. Now, two variables share a storage address. $ A = & $ B ;. In fact, $ a has to share a room with $ B regardless of its original storage address. Therefore, any change to the storage address value will affect the two values.

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

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

The above example is very simple. If a <10 is used as the judgment condition and the condition is true, a is assigned to result []. The reference of result is passed into the function, it adds the generated by each Recursion to the result array result. 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 is interesting in this example is the value of echo. I believe many people think it is 12345678910. In fact, it is 1098765432. Why? Because the function has performed the next function recursion before it executes echoa. Echo a is actually executed when the condition a <10 is not met, echo a returns the result. For the previous layer, after the recursive function is executed, the echo $ a of the current layer is executed, and so on.

Use global variables

Make sure that you understand what global variables are. Global declares in the function that the variable is a reference of the same name of the external variable. The variable is still within the scope of this function. Changing the values of these variables naturally changes the values of external variables with the same name. However, once & is used, variables with the same name are no longer referenced by the same name. Using global variables to implement recursive functions does not need to understand such a deep layer. We can understand recursive functions simply by keeping the original view of global variables.

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

Use static variables

We often see static in the class. Today we use it in recursive functions. Remember the role of static: Initialize the variable only when the function is called for the first time, and keep the variable value.

Example:

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

What is the execution result of this code? Is it 00000? No. It is 01234. First, call test () and static to initialize $ count for the first time. The value of $ count will be retained after each execution and will not be initialized, it is equivalent to directly ignoring the static $ count = 0; statement.

So it is conceivable to apply static to recursive functions. Variables that need to be used as the bridge between recursive functions are initialized using static. The value of bridge variable is retained for each recursion.

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

Summary

The so-called recursive function focuses on how to process the function call itself and how to ensure that the required results can be reasonably "transferred" between functions. Of course, there is also a need to pass between functions that are worthy of recursion, for example:

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

In the face of such a function, we don't have to worry about it. By the way, a deep understanding of variable reference knowledge is of great benefit to solving such problems.

Finally, I would like to share with you a php method for implementing recursion and unlimited classification. The specific implementation method is as follows:

<? Phpecho"

"; $ Area = array ('id' => 1, 'region' => '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 district', 'pid '=> 1), array ('id' => 21, 'area '=> 'nanning City', 'pid '=> 2), array ('id' => 45, 'area' => 'fuzhou City ', 'pid '=> 4), array ('id' => 113, 'area' => 'Asian games cune', 'pid '=> 11 ), array ('id' => 115, 'area '=> 'Olympic cune', 'pid' => 11), array ('id' => 234, 'area '=> 'wuming County', '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 ['region']."
"; // Output here, to see the effect $ list [] = $ v; t ($ arr, $ v ['id'], $ lev+ 1 );}} return $ list;} $ list = t ($ area); echo" "; Print_r ($ list);?>

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.