A recursive function is just a function that calls itself.
Things to take care of Using Recursive Function
1. Every recursive function must have the terminating condition
2. The function must call the function itself and Each recursive call must be different than the one before.
Example
1)
// Factorial example (ie 5 * 4 * 3 * 2 * 1)
function factorial($n) {
if ($n == 1) return 1;
return $n * factorial($n-1);
}
echo factorial(5); // Outputs 120
2)
// Nested Array Summing Example
$example = array(1, 2, array(10,20,30), 4);
function sum_array($array) {
$total = 0;
foreach ($array as $element) {
if(is_array($element)) {
$total += sum_array($element);
} else {
$total += $element;
}
}
return $total;
}
echo sum_array($example); // Outputs 67
No comments:
Post a Comment