Home  >  Q&A  >  body text

Revealing the secrets of recursive functions in PHP for ordinary people

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粉211600174P粉211600174342 days ago659

reply all(2)I'll reply

  • P粉709307865

    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()...).

    reply
    0
  • P粉604669414
  • Cancelreply