Calculate factorial of a number in PHP

Factorial calculation is really cool thing. In mathematics the factorial calculation follows nice rules. In PHP the factorial can be calculated in different ways. Lets first consider recursive way of finding out factorial of a number.

Math example

Lets first see how to calculate the factorial of number 5 mathematically 5! = 5 x 4 x 3 x 2 x 1 5! = 120

PHP code snippet

function getFactorial($num){ static $total = 1; $total = $total * $num--; return ($num > 0) ? getFactorial($num) : $total; } echo "The factorial of 5 is: " . getFactorial(5);

Output

The factorial of 5 is: 120

Comments