Q:

PHP Displaying File List repetition

Having a problem with my code where I have a routine that lists the files in a directory and you can select one of them to correspond to some table entries (in this case files to be associated with a particular mp3).   The code I have devised below lists all the files once for the first entry but for the second entry lists all of them twice.   I don't understand what has gone wrong...
for ($k=0; $k < $_SESSION[CampaignTrax]; $k++) {
                        $numIncrement = $k +1;

$artistConcentrate = $_POST["ArtistField_".$numIncrement];
$titleConcentrate = $_POST["TitleField_".$numIncrement];
$mixConcentrate = $_POST["MixField_".$numIncrement];
$trackfileConcentrate = "trackFile".$numIncrement;

$myDirectory = opendir(".");

while($entryName = readdir($myDirectory)) {
    $dirArray[] = $entryName;
}

closedir($myDirectory);

$indexCount = count($dirArray);

sort($dirArray);

echo "<tr><td>".$numIncrement."</td><td>".$artistConcentrate."</td><td>".$titleConcentrate."</td><td>".$mixConcentrate."</td><td><select name=\"".$trackfileConcentrate."\"><option value=\"\">Select File...</option>";

 for($index=0; $index < $indexCount; $index++) {
        if (substr("$dirArray[$index]", 0, 1) != ".") { // don't list hidden files
 echo "<option value=\"".$dirArray[$index]."\">".$dirArray[$index]."</option>";
 }

}

echo"</select></td></tr>";
}

echo "</table>";

It's probably something simple and as always all help appreciated.
CP

A:

The issue is that the next time you loop the parent "for" loop the old values of dirArray still exist. All you need to do is to initialize it to an empty array before filling it each time.
Change:
while($entryName = readdir($myDirectory)) {
    $dirArray[] = $entryName;
}

to:
$dirArray = array();
while($entryName = readdir($myDirectory)) {
    $dirArray[] = $entryName;
}

You could also change it to:
$dirArray = scandir($myDirectory);

