Recursion (http:/en.wikipedia.org/wiki/Recursive) is a mechanism in which a function calls itself (directly or indirectly). This powerful idea can make some complex concepts extremely simple. . This article mainly introduces the detailed implementation examples of recursion in PHP. Friends who need it can refer to
Definition of recursion
Recursion (http :/en.wikipedia.org/wiki/Recursive) is a mechanism in which a function calls itself (directly or indirectly). This powerful idea can make some complex concepts extremely simple. Outside of computer science, especially in mathematics, the concept of recursion is common. For example: the Fibonacci sequence, which is most commonly used to explain recursion, is a very typical example, and others such as hierarchy (n!) can also be transformed into recursive definitions (n! = n*(n-1)!) .
A recursive function is a function that calls itself. Be careful when writing recursive functions, as they may recurse indefinitely. You must ensure that there are adequate means to terminate recursion.
1: Use parameter reference to complete the recursive function. The operation is the same memory address.
Two: Use global variables to complete the recursive function.
A real global variable imported with the global statement inside the function domain actually establishes a reference to the global variable. In the example, $i inside the test() function is actually just an application of the variable $i in the first line of the program ($i = 1;);
Three: Use static variables to complete the recursive function.
The role of static: initialize the variable only when the function is called for the first time, and retain the variable value.
Example 1. Recursively traverse all files in a folder using global variables
function getFiles($dir) { global $arr; if(is_dir($dir)){ $hadle = @opendir($dir); while($file=readdir($hadle) ) { if(!in_array($file,array('.', '..')) ) { $dirr = $dir.'/'.$file; if(is_dir($dirr)) { getFiles($dirr); }else{ array_push($arr, $dirr); } } } } } $arr = array(); getFiles('E:/logs'); print_r($arr);
Example 2: Recursively traverse all files in a folder using static variables
function getFiles ($dir) { static $arr = array(); if(is_dir($dir)){ $hadle = opendir($dir); while($file=readdir($hadle)) { if(!in_array($file,array('.','..')) ) { $dirr = $dir."/".$file; if(is_dir($dirr)) { getFiles ($dirr); }else{ array_push($arr,$dirr); } } } } return $arr; } $rows= array(); $rows = getFiles ('E:/logs'); print_r($rows);
Related recommendations:
Detailed explanation of PHP recursive algorithm
The above is the detailed content of Detailed explanation of recursion in PHP. For more information, please follow other related articles on the PHP Chinese website!