PHP

Understanding Recursive Functions with and without Stepping in PHP

This PHP code demonstrates the use of recursive functions with two examples: a normal recursive function that increments a number until a specified condition is met, and a recursive function with stepping, which increments by a specified step value.

CODE:

<?php

function normalRec($number)
{
    if ($number >= 7) {
        return;
    }

    echo $number . "<br>";
    $number++;
    normalRec($number);
}
echo "Normal Recursive function without stepping<br>";
normalRec(1);

echo "<br>Recursive function with stepping<br>";

function recur($startingPoint, $endPoint, $steps = 1)
{
    if ($startingPoint >= $endPoint) {
        return;
    }
    $startingPoint = $steps + $startingPoint;
    echo $startingPoint . "<br>";
    recur($startingPoint, $endPoint, $steps);
}

recur(20, 30, 2);
?>

OUTPUT:

Normal Recursive function without stepping
1
2
3
4
5
6

Recursive function with stepping
22
24
26
28
30

Leave a comment