A recursive function is a function that calls itself. Be careful when writing recursive functions, because they can be recursive indefinitely. It is important to ensure that there are adequate methods to terminate recursion.
One: Use the parameter reference to complete the recursive function. The same piece of memory address is being manipulated.
<?php
$i=1;
function
test(&$i)
{
echo
$i;
$i++;
if
($i <10)
{
test($i);
}
}
test($i);//
输出123456789
test
(
$i
);//
输出10
?>
Second: Use global variables to complete the recursive function. A real global variable imported with the global statement inside a function field actually establishes a reference to a global variable. In the example, the $i inside the test () function is actually just one application of the variable $i in the first line of the program ($i = 1;);
<?php
$i
=
1
;
function
test
()
{
global
$i
;
echo $i
;
$i++;
if ($i
<10)
{
test();
}
}
test();//
输出123456789
test
();//
输出10
?>
Three: Use static variables to complete the recursive function. static function: Initializes the variable only the first time it is called, and retains the value of the variable.
<?php
function
test
()
{
static
$i
=
1
;
echo
$i
;
$i
++;
if (
$i
<
10
) {
test
();
}
$i
--;//
在每一层递归结束时自减,这一句可以帮助理解递归函数的执行过程
}
test();//
输出123456789
test();//
输出123456789
?>
Example 1. cases where global variables are used recursively traverse all files under a folder
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 under a folder using a static variable
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);
Implementation of recursion in PHP (with example)