# PHP Function To Work Out Factorial Numbers

8th October 2008 - 2 minutes read time

Factorial of a number is defined as the product of the number and all of the numbers small than it. So if you take the number 4 the factorial of that number is 24 or 1 x 2 x 3 x 4.

Factorials are useful for a number of applications, for example when working out how many times a set of objects can be combined in different ways.

Use the following PHP function to work out the factorial of any given number. The first thing it does it make sure that the number is greater than 1 because the factorial of the number 1 is 1.

``````
function factorial(\$number){
\$result = 1;
if(\$number > 1){
for(\$i = 2; \$i <= \$number; \$i++){
\$result *= \$i;
}
}
return \$result;
}``````

The function works by using the *= operator, which does a calculation between the left and right sides (in this case multiplication) and stores the result on the left hand side. This operator is much like the += operator, and works in the same way.

An alternative of this is the GMP function gmp_fact(). GMP is a set of maths functions that can be used to do some special things like add very large numbers together. It has been part of the PHP core since version 4.0.4.

Beware that factorial numbers can get very large, very quickly. For example, the factorial of the number 50 is 30,414,093,201,713,375,576,366,966,406,747,986,832,057,064,836,514,787,179,557,289,984. Calculating a number this large is not possible without using the GMP functions, but not only that, it will also take a while to calculate it.

Hello Philip,

I don't think you are keeping track of your article.

We are now 2021, your article was written in 2008 =13 years

sofi morris (Wed, 03/10/2021 - 00:23)