Write a recursion function to calculate the factorial of any number?

Factorial calculation is a good suit for recursion function. Recursive function is the function that gets call by itself. The self calling is stopped based on a condition inside the recursive function.

It is not recommeded to initialize value inside recursive function. If you are in need of keeping track of a variable and sum the values at the end then it's better to pass that as recurvise function parameters.

Following a PHP recursive function to calculated the factorial.

function getFactorial($number, $total = 1){
    $total = $total * $number--;
    return ($number > 0) ? getFactorial($number, $total) : $total;
}

echo "Total" + getFactorial(5);

Comments