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.
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;
}
}