PHP/Functions/Function Recursion

Материал из Web эксперт
Перейти к: навигация, поиск

A recursive function is a function that calls itself from within its own code.

 
<?php
     function gcd($a, $b) {
          return ($b > 0) ? gcd($b, $a % $b) : $a;
     }
?>



Define recursive function to delete directories

<?php
   function delete_directory($dir) {
      if ($dh = @opendir($dir)) {
          while (($file = readdir ($dh)) != false) {
             if (($file == ".") || ($file == "..")) continue;
                if (is_dir($dir . "/" . $file))
                   delete_directory($dir . "/" . $file);
                else
                   unlink($dir . "/" . $file);
          }
          @closedir($dh);
          rmdir($dir);
      }
   }
$dir = "./fakeDir";
delete_directory($dir);
?>



Function Recursion Demo

<html>
<head>
<title>Recursion</title>
</head>
<body>
<?php
     function cnt_backwards($from) {
          $from--;
          if($from <= 1) {
               print($from);
               return;
          }
          print($from);
          cnt_backwards($from);
     }
     cnt_backwards(5);
?>
</body>
</html>



Recursive Function Example

 
<?php
function sum_up_to($number) {
    $result = 0;
    for ($i = 1; $i <= $number; $i++) {
        $result += $i;
    }
    return $result;
}
function sum_up_recursive($number) {
    return ($number) ? ($number + sum_up_recursive($number - 1)) : 0;
}
echo "<p>Regular version = ", sum_up_to(42), "</p>\n";
echo "<p>Recursive version = ", sum_up_recursive(42), "</p>\n";
?>



Recursive Functions

 
function factorial($number) {
            if ($number =  = 0) return 1;
            return $number * factorial($number--1);
    }
    print factorial(6);



Using a recursive function to sum an integer set

 
<?
function summation ($count) {
     if ($count != 0) :
          return $count + summation($count-1);
     endif;
}
$sum = summation(10);
print "Summation = $sum";
?>