How to create a reverse loop to find the first match file

What I'm looking for is a way to create a function in which a child folder goes through it and back in the directory hierarchy to find the first matching file that is listed.

Example: I can say that I have a directory structure: Home / Folder 1 / Folder 2 / Folder 3

And I'm looking for a style.css file.

I would like to start pointing to the child folder (Folder 3) and look for style.css, and if it is not there, it will continue the parent folder (Folder 2) and so on. But he should not go further than Folder 1.

If anyone has a good idea, how with that I will be very grateful!

+4
source share
3 answers

Quick and dirty way:

function traverse_backward($filename, $path, $min_depth) { // $path = '/home/user/projects/project1/static/css/'; // $min_depth - the minimum level of the path; // $filename - the file name you are looking for, eg 'style.css' $path_parts = explode('/',$path); while (count($path_parts) > $min_depth) { $real_path = implode($path_parts,'/').'/'; if (is_file($real_path.$filename)) { return $real_path; } array_pop($path_parts); } return false; } traverse_backward('t.php', '/home/user/projects/test-www/static/css', 3); 
+3
source

Further explanation of the answer to the fist: when working with paths in PHP it is convenient to detonate () the path into an array. It’s easier to work with paths if they are in an array. In this case, you use array_pop () to remove the last element of the array with each iteration of the loop. Then you can use implode () on the path to return it to a string, the string can be used with file functions such as file_exists ().

+1
source

This is a simple recursive function (you have a limited number of possible iterations, so there will be no overhead). The pseudocode is as follows:

 function lookForCss($from) { if(from contains css file) { return $from; } //else $from = go up one folder($from); return lookForCss($from); } 
0
source

All Articles