PHP Program to find the factorial of a number

bookmark

<?php
    //program to find factorial of a number
    //here, we are designing a function that
    //will take number as argument and return
    //factorial of that number
    
    //function: getFactorial
    function getFactorial($num){
        //declare a variable and assign with 1
        $factorial = 1;
        for($loop = 1; $loop <= $num; $loop++)
            $factorial = $factorial * $loop;
        return $factorial;
    }

    //Main code to test above function
    $number = 1;
    print_r("Factorial of ".$number. " is = ".getFactorial($number). "\n");
    $number = 2;
    print_r("Factorial of ".$number. " is = ".getFactorial($number). "\n");
    $number = 3;
    print_r("Factorial of ".$number. " is = ".getFactorial($number). "\n");
    $number = 4;
    print_r("Factorial of ".$number. " is = ".getFactorial($number). "\n");  
    $number = 5;
    print_r("Factorial of ".$number. " is = ".getFactorial($number). "\n");    
?>


Output
Factorial of 1 is = 1
Factorial of 2 is = 2
Factorial of 3 is = 6
Factorial of 4 is = 24
Factorial of 5 is = 120