PHP检查文件是否存在于任何目录中

时间:2018-04-21 10:42:05

标签: php file-exists

如何检查任何目录中是否存在文件,添加到$notexists数组中。

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[] = '';
    }
}

3 个答案:

答案 0 :(得分:3)

您需要等到循环结束才能知道是否在任何目录中找不到该文件。

continue;应为break;continue重新启动会启动当前循环的下一次迭代,但是一旦找到要完全退出循环的文件。

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;
    }
}

答案 1 :(得分:0)

您可以使用array_diff()检查未找到的文件:

foreach($files as $file){
   foreach ($folders as $this_folder) {
     if (file_exists($this_folder.$file)) {
        $exists[] =$file;
        break;
     }
}
$notexists = array_diff($files, $exists);

答案 2 :(得分:0)

您可以在else条件之后直接存储它们,因为您使用break;不必担心迭代

foreach($files as $file){
 foreach ($folders as $folder_path) {

   /* NOTE : the '@' here before the file_exists() function 
      is to manage this function errors by yourself after the `else` condition , 
      otherways you can remove it to see the native php errors .
      */

   if (@file_exists($folder_path.$file)) {
   $exists[] = $file;
   break;

   }else{
   $notexists[] = $file;
   }
 }
}

结果:

  

存档文件:Array ( [0] => index.php [1] => head.php )
   不存在的:Array ( [0] => random_file.random )

但请注意,在条件中使用它们之前需要先定义这些数组,以便以后在循环它们时返回空数组时不会得到未定义的错误。
所以在你的第一个foreach()添加那些变量定义之前

$exists    = array();
$notexists = array();
$folders   = array('./'); // your folders list ofc should be here ..