I currently have an array which holds file names, I now want to foreach
through this array using a wildcard search in a directory and find the matching files.
How can I do this using the glob()
function?
I currently have an array which holds file names, I now want to foreach
through this array using a wildcard search in a directory and find the matching files.
How can I do this using the glob()
function?
You can simply do this to extract each file which matches your wildcard search inside a foreach loop:
$search = "*.txt";
// if this is what you mean by indexed string variable?
$file = array("updated.txt", "new.txt");
// getcwd() will retrieve the current directory but is not needed - this just shows
// that you can supply a directory if you wanted to.
function MatchFile($file,$search)
{
$temp = array();
$i = 0;
foreach (glob(getcwd().$search) as $filename) :
if (count($file) > $i):
array_push($temp, ($filename == $file[$i++])? $filename : "");
else:
// stops the index overflow error
break;
endif;
endforeach;
return $temp;
}
foreach (MatchFile($file,$search) as $found):
echo $found . " was found!";
endforeach;
This is just a replacement of opendir();
.
If you're still unsure or need to know more flags, you can use this link for help.