PHP and Javascript Recursive Functions

Hello Pretty Brain ...

It's been a few seconds ... We hope your world has found some progress.

This tutorial is about repetitive functions.

There are many times where a programmer will have to repeat a certain piece of code till a certain condition is met.

Both PHP and Javascript have functionality to perform recursion; mainly the loops.

But there are scenarios best suited for what programmers call repetitve/recursive functions.

A recursive function executes itself repeatedly till a certain condition is met. We'll do a couple of examples and skidaddle.

This is an example of a PHP recursive function.

<?php 
    $count = 0;
    function repeatMe ($count) {
        if ($count < 10) {
            return repeatMe($count++);
        } 

    }
?>

The function repeatMe will keep executing itself until $count is greater or equal to 10. After which it'll break the iteration and consequently; its execution.

Please be careful and ensure that the condition that breaks the iteration is ultimately met. Otherwise you'll be running an infinite loop driving your memory up the wall.

This is an example of a recursive function in Javascript:

<script>
    var count = 0;
    function repeatMe (count) {
        if (count < 10) {
            return count + 1;
        }

        return count;
    }
</script>

Please note that these two are quite similar. Hopefully it makes it easier to interchange the languages.

"Ensure that the condition that breaks the iteration is ultimately met."

The Village Geek

Hopefully you'll be using recursive functions in your code soon.

Ayytt do your thing, get back to coding.

Get cracking

Ciao


Cape Town, South Africa

Buy me a coffee ? :) Buy me a coffee :)

Reply to this discussion

Bookmarks

Build
Learn
Coming Soon ...