Reputation: 9466
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[] = '';
}
}
Upvotes: 0
Views: 1208
Reputation: 19780
You could use array_diff()
to check the files that was not found:
foreach($files as $file){
foreach ($folders as $this_folder) {
if (file_exists($this_folder.$file)) {
$exists[] =$file;
break;
}
}
$notexists = array_diff($files, $exists);
Upvotes: 0
Reputation: 165
you could store them directly after else
condition since your using break;
you dont have to worry about iteration
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;
}
}
}
RESULT :
Exist Files :
Array ( [0] => index.php [1] => head.php )
Non Exist ones :Array ( [0] => random_file.random )
but be aware that you need to define those arrays before you use them inside the conditions so you dont get undefined errors later if they return an empty array when you loop them as a result .
so before your first foreach()
add those variables definition
$exists = array();
$notexists = array();
$folders = array('./'); // your folders list ofc should be here ..
Upvotes: 0
Reputation: 780688
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;
}
}
Upvotes: 3