PHP Recursive Functions

In this lesson, you will learn about Recursive Functions in PHP, and their usages, along with examples to better understand the topic.


PHP Recursive Function

A function that calls itself repeatedly is referred to as recursive until a condition is fulfilled. Recursive functions are often used to solve complex mathematical calculations and process deeply nested constructions, e.g., to print all the components of a deeply nested array. Be careful when creating recursive functions because poorly written code can result in endless loops.

PHP also promotes recursive calling functions such as C/C++. In such a case, we call the current function within the function, and it’s also called recursion. It is advised against calling recursive functions more than 200 times (Depending on the processor speed), which can crash the stack and cause script termination.

Flowchart of Recursive Function

 

Example

<?php
echo "PHP ***Recursive*** Function Example";
echo "<br>";

echo " ------------Example (1)------------------ ";
echo "<br>";

function factorialFunc($numericvar)
{
    if ($numericvar < 0) return -1; /*Wrong value*/
    if ($numericvar == 0) return 1; /*Terminating condition*/
    return ($numericvar * factorialFunc($numericvar - 1));
}
echo factorialFunc(5);
echo "<br>";
echo " ------------Example (2)------------------ ";
echo "<br>";
function recursiveFunc($numericvar)
{
    if ($numericvar <= 10)
    {
        echo "$numericvar <br/>";
        recursiveFunc($numericvar + 1);
    }
}
recursiveFunc(5);
?>

Output

PHP ***Recursive*** Function Example
------------Example (1)------------------
120
------------Example (2)------------------
5
6
7
8
9
10

This concludes the PHP Recursive Functions lesson. In the next lesson, you will learn about PHP Math Functions.