Google “recursive functions”. Odds are that you’ll stumble upon a tutorial that explains this wondrous concept using the worst examples available.
Take this little snippet that I wrote by myself:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <?php function factorial($x) { if(!is_numeric($x) || $x<1) return 1; return factorial($x-1)*$x; } function fibonacci($x) { if(!is_numeric($x) || $x<0) return 0; else if($x==1) return 1; return fibonacci($x-1) + fibonacci($x-2); } $a = 6; $b = factorial(a); // factorial(6) = 720 $c = fibonacci(a); // fibonacci(6) = 8 echo "Factorial: $b<br/>\n"; echo "Fibonacci: $c<br/>\n"; > |
The problem with these two examples is that by being recursive they use up far too many resources than if they had not been recursive.
The following code omits the use of recursive functions.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | function factorial($x) { if(!is_numeric($x) || $x<1) return 1; $y = 1; do { $y *= $x; $x--; } while($x>1); return $y; } function fibonacci($x) { if(!is_numeric($x) || $x<1) return 0; $y = 1; $x2 = 1; do { $x1 = $x2; $x2 = $y; $y = $x1 + $x2; $x--; } while($x>1); return $y; } |
These two non-recursive functions would arguably utilise less memory and cpu cycles than the recursive ones.
But when is it a good idea to use recursive functions? Take a recursive copy function, for example. The easiest way to create this function is to make it recursively call itself.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php function cp_r($src, $dst) { if(file_exists($dst)) return; if(is_dir($src)) {s mkdir($dst); $files = scandir($src); foreach($files as $file) { if($file != '.' || $file != '..') cp_r("$src/$file", "$dst/$file"); } } else if(file_exists($src)) copy($src, $dst); } cp_r("/home/user/my_old_dir", "/home/user/my_new_dir"); ?> |
Compare the previous implementation to the following.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php function cp_r($src, $dst) { $files = array(""); do { $file = array_pop($files); if(is_dir($src.$file)) { mkdir($dst.$file); $tmp = scandir($src.$file); foreach($tmp as $val) array_push($files, $file.'/'.$val); } else if(file_exists($src.$file)) copy($src.$file, $dst.$file); } while(!empty($files)); } cp_r("C:\\usr\\src", "C:\\usr\\dst"); ?> |
Resources used by these two functions will theoretically be the same. As such, both implementations are equally valid.
My main issue with the tutorials is that their examples teach people who are new to this concept something which they undoubtedly will understand as unneeded. Using recursive functions to calculate factorials or Fibonacci numbers has too many downsides to be used as an example of recursive functions. Please use proper examples.

