0

My problem is this: I have an array in which I collect all the files of a hard disk, like:

$files = Array(
    [0] => E:\\folder1\file1.mp4
    [1] => E:\\folder1\folder1a\file2.mp4
    [2] => E:\\folder2\folder2a\file3.avi
    [3] => E:\\folder2\folder2a\file4.avi
    [4] => E:\\folder2\folder2a\file5.avi
    [5] => E:\\folder2\folder2a\file6.avi
    [6] => E:\\folder2\folder2a\file7.avi
    [7] => E:\\folder2\folder2a\file8.mkv
    [8] => E:\\folder2\folder2a\file9.avi
    [9] => E:\\folder2\folder2a\file10.avi
    [10] => E:\\folder2\folder2a\file1.mp4
...
   [2345] => E:\\folder324\folder324a\folder324aa\file5456789.mp4
)

In this array I would like to find all the duplicate names, regardless of the case and the folders in which they are located and then display an echo in order to print on screen this:

file1.mp4 is duplicated in:
E:\\folder1\
E:\\folder2\\folder2a\\

I tried this:


foreach($files as $ind => $c) {
    $name = basename($c); 
    $dups[] = $name;
}
    
foreach (array_count_values($dups) as $indd => $rty) {
    if ($rty > 1) echo $indd . " is duplicated in: <br/>";
}

But I don't know how to view folders.

smal
  • 15
  • 5
  • Related: [Find duplicate files by names with PHP](https://stackoverflow.com/q/13471336/2943403) and [php duplicate a file in other folders](https://stackoverflow.com/q/12059465/2943403) and [Extract basename from filename in array](https://stackoverflow.com/q/10131213/2943403) – mickmackusa Dec 18 '22 at 22:58

1 Answers1

1

You need to keep track of the directories in which the file is, so first build up a list of the directories using the filename as the key...

$dups = [];
foreach ($files as $c) {
    $dups[basename($c)][] = dirname($c);
}

Second loop over this and if there is more than one directory (the count() is > 1) then echo out the key (the filename) and the directories (using implode() to show them together)...

foreach ($dups as $fileName => $rty) {
    if (count($rty) > 1) {
        echo $fileName . ' is duplicated in: ' . implode(', ', $rty) . PHP_EOL;
    }
}
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • Thanks for your help. I just point out that the code I was looking for is:: ` foreach($files as $ind => $c) { $name = basename($c); $dups = []; } foreach ($files as $c1) { $dups[basename($c1)][] = dirname($c1); } foreach ($dups as $fileName => $rty) { if (count($rty) > 1) { echo '' . $fileName . ' is duplicated in:
    ' . implode('
    ', $rty) . PHP_EOL; echo "
    "; } `
    – smal Dec 18 '22 at 18:05
  • @smal, looks like your first `foreach` loop doesn't do anything useful. – Nigel Ren Dec 18 '22 at 18:09