Can anyone explain to me recursive functions in PHP (without using Fibonacci) in layman's terms and using examples? I'm looking at an example but Fibonacci is completely lost on me!
Thank you in advance ;-) Also, how often do you use them in web development?
P粉7093078652023-10-18 00:23:39
One example would be to print every file in any subdirectory of a given directory (if there are no symlinks in those directories, this might break the functionality in some way). The pseudo code to print all files is as follows:
function printAllFiles($dir) { foreach (getAllDirectories($dir) as $f) { printAllFiles($f); // here is the recursive call } foreach (getAllFiles($dir) as $f) { echo $f; } }
The idea is to print all subdirectories first, then print the files in the current directory. This idea works for all subdirectories, which is why this function is called recursively for all subdirectories.
If you want to try this example, you must check the special directories .
and ..
, otherwise you will get stuck calling printAllFiles(". ")
all the time in this way. Additionally, you have to check what you want to print and what the current working directory is (see opendir()
, getcwd()
...).
P粉6046694142023-10-18 00:03:08
A recursive function is a function that calls itself
If a function keeps calling itself, how does it know when to stop? You set a condition, called a base case. The base case tells our recursive call when to stop, otherwise it will loop infinitely.
For me, a good example to learn from is Factorial一个>. From the comments below it seems like the factorial function is a bit much, I'll leave it here just in case you need it.
function fact($n) { if ($n === 0) { // our base case return 1; } else { return $n * fact($n-1); // <--calling itself. } }
Regarding using recursive functions in web development, I personally do not use recursive calls. Not that I think relying on recursion is bad practice, but they shouldn't be your first choice. If used incorrectly, they can be fatal.
While I can't compete with the directory example, I hope this helps.
It would also be helpful to check this question, where the accepted answer demonstrates in layman's terms how recursive functions work. Although the OP's question involves Java, the concepts are the same,