Find factorial of a number in PHP

Right now, will figure out how to discover factorial of a given number utilizing PHP program?

Given a number and we need to locate its factorial.

Equation to discover factorial: 5! (Factorial of 5) = 5x4x3x2x1 = 120

Example:

    Input: 5
    Output: 120

Program to discover factorial of a number in PHP:

<?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

Leave a Comment

error: Alert: Content is protected!!