Write a PHP script that calculates the factorial of a given number using an iterative approach.

<?php
function calculateFactorial($n) {
    if ($n < 0) {
        return "Factorial is undefined for negative numbers.";
    }

    $factorial = 1;

    for ($i = 2; $i <= $n; $i++) {
        $factorial *= $i;
    }

    return $factorial;
}

$number = 5;
$factorial = calculateFactorial($number);

echo "Factorial of $number is: $factorial";
?>
  • The script defines a function calculateFactorial that calculates the factorial of a given number using an iterative approach.
  • The function checks if the input is a negative number, in which case it returns a message indicating that factorial is undefined for negative numbers.
  • The script then calls the function with a sample number ($number) and prints the result.

Post your Answer