PHP/Functions/Function Recursion

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

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

   <source lang="html4strict">

<?php

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

?>

 </source>
   
  


Define recursive function to delete directories

   <source lang="html4strict">

<?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); ?>

      </source>
   
  


Function Recursion Demo

   <source lang="html4strict">

<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>

      </source>
   
  


Recursive Function Example

   <source lang="html4strict">

<?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 "

Regular version = ", sum_up_to(42), "

\n"; echo "

Recursive version = ", sum_up_recursive(42), "

\n";

?>

 </source>
   
  


Recursive Functions

   <source lang="html4strict">

function factorial($number) {

           if ($number =  = 0) return 1;
           return $number * factorial($number--1);
   }
   print factorial(6);
 
 </source>
   
  


Using a recursive function to sum an integer set

   <source lang="html4strict">

<? function summation ($count) {

    if ($count != 0) :
         return $count + summation($count-1);
    endif;

} $sum = summation(10); print "Summation = $sum"; ?>

 </source>