What in layman's terms is a Recursive Function using PHP

前端 未结 16 1354
庸人自扰
庸人自扰 2020-11-22 05:50

Can anyone please explain a recursive function to me in PHP (without using Fibonacci) in layman language and using examples? i was looking at an example but the Fibonacci to

16条回答
  •  甜味超标
    2020-11-22 06:16

    An example would be to print every file in any subdirectories of a given directory (if you have no symlinks inside these directories which may break the function somehow). A pseudo-code of printing all files looks like this:

    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 sub directories first and then the files of the current directory. This idea get applied to all sub directories, and thats the reason for calling this function recursively for all sub directories.

    If you want to try this example you have to check for the special directories . and .., otherwise you get stuck in calling printAllFiles(".") all the time. Additionally you must check what to print and what your current working directory is (see opendir(), getcwd(), ...).

提交回复
热议问题