Finding files and directories using recursion

Quite often, we need to find all the files inside a directory. This includes all subdirectories inside it and also directories inside those subdirectories. As a result, we need a recursive solution to find the list of files from the given directory. The following example will show a simple recursive function to list all the files in a directory:

function showFiles(string $dirName, Array &$allFiles = []) { 
$files = scandir($dirName);

foreach ($files as $key => $value) {
$path = realpath($dirName . DIRECTORY_SEPARATOR . $value);
if (!is_dir($path)) {
$allFiles[] = $path;
} else if ($value != "." && $value != "..") {
showFiles($path, $allFiles);
$allFiles[] = $path;
}
}
return;
}

$files = [];

showFiles(".", $files);

The showFiles function actually takes a directory and first scans the directory to list all the files and directories under it. Then, with a foreach loop, it iterates through each file and directory. If it is a directory, we recall the . function again to list the files and directories under it. This continues until we traverse all the files and directories. Now, we have all the files under the $files  array. Now, let's show the files using a foreach loop sequentially:

foreach($files as $file) {
echo $file." ";
}

This will have the following output in the command line:

/home/mizan/packtbook/chapter_1_1.php
/home/mizan/packtbook/chapter_1_2.php
/home/mizan/packtbook/chapter_2_1.php
/home/mizan/packtbook/chapter_2_2.php
/home/mizan/packtbook/chapter_3_.php
/home/mizan/packtbook/chapter_3_1.php
/home/mizan/packtbook/chapter_3_2.php
/home/mizan/packtbook/chapter_3_4.php
/home/mizan/packtbook/chapter_4_1.php
/home/mizan/packtbook/chapter_4_10.php
/home/mizan/packtbook/chapter_4_11.php
/home/mizan/packtbook/chapter_4_2.php
/home/mizan/packtbook/chapter_4_3.php
/home/mizan/packtbook/chapter_4_4.php
/home/mizan/packtbook/chapter_4_5.php
/home/mizan/packtbook/chapter_4_6.php
/home/mizan/packtbook/chapter_4_7.php
/home/mizan/packtbook/chapter_4_8.php
/home/mizan/packtbook/chapter_4_9.php
/home/mizan/packtbook/chapter_5_1.php
/home/mizan/packtbook/chapter_5_2.php
/home/mizan/packtbook/chapter_5_3.php
/home/mizan/packtbook/chapter_5_4.php
/home/mizan/packtbook/chapter_5_5.php
/home/mizan/packtbook/chapter_5_6.php
/home/mizan/packtbook/chapter_5_7.php
/home/mizan/packtbook/chapter_5_8.php
/home/mizan/packtbook/chapter_5_9.php
These were solutions for some common challenges we face during development. However, there are other places where we will use recursion heavily, such as binary search, trees, divide and conquer algorithm, and so on. We will discuss them in the upcoming chapters.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset