Recursive Function Example : Function Recursion « Functions « PHP






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








Related examples in the same category

1.Define recursive function to delete directories
2.Function Recursion Demo
3.A recursive function is a function that calls itself from within its own code.
4.Using a recursive function to sum an integer set
5.Recursive Functions