php – How to create a backwards loop to find first matching file – Education Career Blog

What I’m looking for is a how to build a function that takes a child folder an loops through it and backwards in the directory hierarchy to find the first matching file that is specified.

A example is that i lets say i have the directory structure:
Home / Folder 1 / Folder 2 / Folder 3

And I’m looking for the file style.css.

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

If anybody have a good idea how do to this I would be very grateful!


A quick and dirty way would be:

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, e.g. '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;

    return false;
traverse_backward('t.php', '/home/user/projects/test-www/static/css', 3);


Further explanation for the fist answer: When working with paths in PHP, it is convenient to explode() the path in to 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 put it back in to a string, the string can be used with file functions such us file_exists().


This is a simple recursive function (you have a limited amount of possible iterations, so there won’t be much overhead). The pseudocode is like this:

function lookForCss($from) {
  if(from contains css file) {
    return $from;
  $from = go up one folder($from);
  return lookForCss($from);

Leave a Comment