PHP supports recursion, or in simple words, we can call a PHP function within another function without any argument, just like in C++. 200 is considered to be the maximum recursion level to avoid any crash of code.
Example 1: Code for displaying n numbers using recursive function in PHP.
<!DOCTYPE html> <html> <body> <?php function NaturalNumbers($number) { if($number<=10){ echo "$number <br/>"; NaturalNumbers($number+1); } } NaturalNumbers(1); ?> </body> </html> |
Output
1 2 3 4 5 6 7 8 9 10 |
Example 2: Code to generate factorial of a number using recursive function in PHP.
<!DOCTYPE html> <html> <body> <?php function factorial($n) { if ($n < 0) return -1; if ($n == 0) return 1; return ($n * factorial ($n -1)); } echo factorial(10); ?> </body> </html> |
3628800 |
Please Share