Here’s how you can calculate the factorial of a number in PHP using both iterative and recursive approaches:

Iterative Approach:

function factorialIterative($n) {
    $result = 1;
    for ($i = 1; $i <= $n; $i++) {
        $result *= $i;
    }
    return $result;
}

$number = 5; // Change this to the desired number
$factorial = factorialIterative($number);
echo "Factorial of $number is $factorial";

Recursive Approach:

function factorialRecursive($n) {
    if ($n <= 1) {
        return 1;
    } else {
        return $n * factorialRecursive($n - 1);
    }
}

$number = 5; // Change this to the desired number
$factorial = factorialRecursive($number);
echo "Factorial of $number is $factorial";

Both approaches will give you the factorial of the specified number. The iterative approach uses a loop to calculate the factorial, while the recursive approach uses a function that calls itself to calculate the factorial. Keep in mind that the recursive approach might lead to stack overflow errors for very large numbers due to excessive function calls.

Leave a Reply

Your email address will not be published. Required fields are marked *