CodesJava

Easy learning with example program codes

PHP Recursive Functions


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
Posted in PHP   
Sign Up/ Sign In
Ask a Question


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki