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?
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:
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 callingprintAllFiles(". ")
all the time in this way. Additionally, you have to check what you want to print and what the current working directory is (seeopendir()
,getcwd()
...).Layman’s term:
A recursive function is a function that calls itself
Go deeper:
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.