Search code examples
phpfile-exists

PHP check if file not exists in any directory


How to check if a file doesn't exist in any directory, add into the $notexists array.

foreach($files as $file){
   foreach ($folders as $this_folder) {
     if (file_exists($this_folder.$file)) {
        $exists[] =$file;
        continue;
     }else{
         // What to do if file is not exist in any directory, add into array.
         $notexists[] = '';
    }
}

Solution

  • You need to wait until the end of the loop to know if the file was not found in any of the directories.

    And continue; should be break;. continue restarts starts the next iteration of the current loop, but once you find the file you want to exit the loop completely.

    foreach($files as $file){
        $found = false;
        foreach ($folders as $this_folder) {
            if (file_exists($this_folder.$file)) {
                $exists[] =$file;
                $found = true;
                break;
            }
        }
        if (!$found) {
            // What to do if file is not exist in any directory, add into array.
            $notexists[] = $file;
        }
    }