Home > Article > Backend Development > PHP Tutorial: No need to recursively traverse files in a directory_PHP Tutorial
If you want to traverse all files in a directory (including subdirectories), the first idea that comes to mind is to use recursion: first process the current directory, and then process the subdirectories under the current directory. Is it possible not to use recursion? I have seen it before when I was learning data structures. Recursion is actually implemented using the stack. The characteristic of recursion is that it continuously calls itself. The last call is executed first, and the penultimate call is is executed second, and so on, the initial call is executed last. If you understand the principle of recursion, you can actually convert all recursive implementations into non-recursive implementations.
Traverse all files in a directory in a non-recursive way. The idea is mainly divided into three steps:
1. Create an array and put the directory to be traversed; (actually creating a stack)
2. Loop through this array. The condition for the end of the loop is that the array is empty;
3. Each cycle, process an element in the array and delete the element. If the element is a directory, add all the sub-elements in the directory to the array;
The code written according to this idea is as follows:
Copy to ClipboardQuoted content: [www.bkjia.com] /**I don’t think recursion has big disadvantages here. In fact, in many cases, using recursion to design is very concise and readable. As for efficiency issues, it will only have an impact unless the recursion depth is particularly large.
The following is the implementation using recursion for comparison:
Copy to ClipboardQuoted content: [www.bkjia.com] /**It is found during operation that the results of the two functions are slightly different, mainly in the order of printing. The order of the running results of function 1 is reversed because the order of pushing onto the stack is exactly the opposite of the order in which scandir comes out. You can change line 21:
Copy to ClipboardQuoted content: [www.bkjia.com] $children = array_reverse(scandir($file));The results will be exactly the same.
Source of this article: http://blog.quanhz.com/archives/210