Search code examples
phpdirectory-structure

RecursiveDirectoryIterator - signal upon first instance of string in path found


I'm using RecursiveDirectoryIterator(). I have a situation whereby I want to signal to my program that there should be a single file created upon the first instance of a specified string in a directory hierarchy. I'm hoping that RecursiveDirectoryIterator() is suitable for this, but if there's another option that would make more sense, I'm also open to that.
See below for details on my question... Thanks.

code:

$in_dir = 'none';
$path = '.';
$dir  = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::SELF_FIRST);

foreach($files as $object){
  //if this is a directory... find out which one it is.
  if($object->isDir()){
    if(strpos($object->getPathname(), 'dir1') == true){
      //i need a file (file1.txt) created here, upon the first instance found
      $in_dir = 'dir1';
    }else if(strpos($object->getPathname(), 'dir2') == true){
      //i need a file (file2.txt) created here, upon the first instance found
      $in_dir = 'dir2';
    }
}

Solution

  • You just need to keep track of the first time you visit the directory...

    $in_dir = 'none';
    $path = '.';
    $dir  = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS);
    $files = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::SELF_FIRST);
    // not seen yet
    $foundDir1 = false;
    $foundDir2 = false;
    
    foreach($files as $object){
        //if this is a directory... find out which one it is.
        if($object->isDir()){
            if(strpos($object->getPathname(), 'dir1') == true){
                //i need a file (file1.txt) created here, upon the first instance found
                if (!$foundDir1) {
                    // first time we've seen it, create file...
    
                    // mark as found
                    $foundDir1 = true;
                }
            }else if(strpos($object->getPathname(), 'dir2') == true){
                //i need a file (file2.txt) created here, upon the first instance found
                if (!$foundDir2) {
                    // first time we've seen it, create file...
    
                    // mark as found
                    $foundDir2 = true;
                }
            }
        }
    }