简体   繁体   中英

remove files in directory not match array

I post array to php try to remove the file in directory but not in array.

Below code foreach can get the file name in array, while get all the files in directory.

I tried the function like below wrong one, put the while in foreach expect find the file not match $row then unlink. But it failed it will remove some files in array.. seems my logic was wrong. did I doing something wrong?

$dir = "img/";

foreach($img_arr as $row) {
    print $row;  // get : 2.png 3.png 0.png    ....
}

$opendir = opendir($dir);
while ($file = readdir($opendir)) {
    // if($file != $row && $file!="." && $file!=".."){
        print $file;  //get : ...2.png 3.png ...0.png   ....
    // }    
}

wrong

$dir = "img/";

foreach($img_arr as $row) {
    print $row;  // get : 2.png 3.png 0.png    ....

    $opendir = opendir($dir);
    while ($file = readdir($opendir)) {
       if($file != $row && $file!="." && $file!=".."){
          print $file;  // expect get the file not match $row
       }    
    }
}

Use in_array to check if file exists in your $img_arr :

$img_arr = array(.....); // here comes your array
$opendir = opendir($dir);
// don't forget to stop while-loop also
while (($file = readdir($opendir)) !== false) {
   if($file!="." && $file!=".." && !in_array($file, $img_arr)){
      print $file;
   }    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM