Recursive function: Call php function itself Recursive function: Call php function itself php php

Recursive function: Call php function itself


Recursive functions are OK - but dangerous if you aren't sure you know what you are doing. If there is any chance that a function will end up in a recursive loop (where it keeps calling itself over and over) you will either time out, run out of memory or cause a zombie apocalypse.

Think of recursive calls as a really, really sharp knife - in the hands of an experienced chef, it's a match made in heaven, in the hands of the dishwasher, it is a lost finger waiting to happen.

PHP tries to play nice, and limits a recursive depth to 100 by default (though this can be changed) but for almost all cases, if your recursive depth gets to 100, the accident has already happened and PHP reacts by stopping any additional pedestrians from wandering into traffic. :)


Fluffeh provided sufficient answer as far as recursive functions are concerned. But when using recursion with large arrays/objects/etc, you should watch optimisation of your code, so that it doesn't take much memory or CPU power to execute.

You could easily optimise your code to be cleaner, take less memory and be more resilient to unexpected data. Notice the & in the function arguments list (it eliminates creating a copy of an array everytime a nested function is called).

function determine(& $the_array){foreach ($the_array as $key => $value) {    switch ($key) {        case 'in':        case 'out':                echo $value;            break;        case 'level':            if (!is_array($value)) break;                echo '<ul>';                determine($value);                echo '</ul>';            break;        }    }}


I dont know, if it's a good solution, but i use this one to call a function from inside itself:

function my_calucar(){    $arrayy= array('mine' => '1',  'yours' => '24', 'her' => '34');    foreach ($arrayy as $each=>$value) {        switch ($each) {        default:                my_calucar($value);        }    }}