Skip to content
Advertisement

Finding a filename match in two directories and writing the matched filename to an array

I have looked on Stackover for a simular issue but can’t find a solution.

I am trying to write a script that looks at the content of two directories to findout if a filename match can be found in both directories. If a match is found write the name of the matched filename to an array.

The first thing I am doing is using””scandir” to create an array of data from the first directory. In the “foreeach”loop through the array from the “scandir” result and perform a “file_exists” using the variable “$image1” to fing a match in the seconds directory “allimages/boardsclean”. If a match is found write the filename to the “$found_images” array.

Testing the result of the “$found_images” array I am not seeing the result I was expecting.

Can anyone see where I am going wrong?

$c1 = 0;
$c2 = 0;
$scan = scandir('allimages/temp1');

$found_images = array();
foreach ($scan as $image1) {
    if (file_exists('allimages/temp1/'.$image1) && ('allimages/temp2/'.$image1)) {
            echo "file match in Scan $image1</br>";
            $found_images[] = 'allimages/adminclean/'. $image1;
      $c1++;
        } 
}
echo $c1."</br>";

foreach ($found_images as $image3) {
    echo "file match $image3 </br>";
    $c2++;
}
echo $c2."</br>";

Advertisement

Answer

First, you don’t need to test for the file from the scandir because, well… it’s already there and was returned. Second, you don’t test for the one in the second directory. You need:

if(file_exists('allimages/temp2/'.$image1)) {

However, just scan both directories and compute the intersection of the returned arrays which will give you files common to both directories. It’s as simple as:

$found = array_intersect(scandir('allimages/temp1'), scandir('allimages/temp2'));

Then you can filter out directories if you want and add allimages/adminclean/ in the array or when needed.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement