﻿ PHP Function Exercise: Create a function to calculate the factorial of a positive number - w3resource # PHP function Exercises: Create a function to calculate the factorial of positive a number

## PHP function: Exercise-1 with Solution

Write a function to calculate the factorial of a number (a non-negative integer). The function accepts the number as an argument.

Pictorial Presentation: Sample Solution:

PHP Code:

``````<?php
function factorial_of_a_number(\$n)
{
if(\$n ==0)
{
return 1;
}
else
{
return \$n * factorial_of_a_number(\$n-1);
}
}
print_r(factorial_of_a_number(4)."\n");
?>
```
```

Sample Output:

```24
```

Flowchart : PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

﻿

## PHP: Tips of the Day

PHP: Anonymous recursive PHP functions

In order for it to work, you need to pass \$factorial as a reference

```\$factorial = function( \$n ) use ( &\$factorial ) {
if( \$n == 1 ) return 1;
return \$factorial( \$n - 1 ) * \$n;
};
print \$factorial( 5 );
```

Ref : https://bit.ly/38dj7jm