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.
Previous: PHP Functions Exercises Home.
Next: Write a function to check a number is prime or not.
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
- New Content published on w3resource:
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- React - JavaScript Library
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework