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.

Lets take a look at a simple example of a recursive function in PHP 

<?php

//Our recursive function.

function recursive($num){
    //Print out the number.
    echo $num, '<br>';
    //If the number is less or equal to 50.
    if($num < 50){
        //Call the function again. Increment number by one.
        return recursive($num + 1);
    }
}

//Set our start number to 1.
$startNum = 1;

//Call our recursive function.
recursive($startNum);

?>

The code above is pretty simple. Basically, the function checks to see if the number is less than 50. If the number is less than 50, then we increment the number and call the function again. This process is repeated until the number has reached 50.

Note that if you need to go deeper than 100 levels, then you will need to increase the xdebug.max_nesting_level setting. You can do this via the ini_set function if you’re on a hosted platform that allows you to modify PHP ini settings on the fly:

<?php

ini_set('xdebug.max_nesting_level', 150);

?>

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> 

Out put : 3628800 

No comments:

Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...