Imaginary folder when I use "DirectoryIterator" in PHP?

128 Views Asked by At

I want to count the number of the files in different folders using PHP. The folder's names are numbers starting from 1 to 26. I have used the iterator_count() PHP function to do that. This is what I have written:

$noCoords = array();
for ($number = 1; $number <= 26; $number++) {
     $x = iterator_count(new DirectoryIterator('/Images/'.$number.'/file'));
     $noCoords[$number] = $x-2; // removing . and .. files
     array_push($noCoords,$x);
}

$noCoords=json_encode($noCoords);
echo($noCoords);

In my web app I use javascript to alert the json returned:

var noCoordsImages = function(){    
        $.get('requestsII/count_noCoords_images.php', function(data) {
            alert(data);
        });
    }

And here I get the problem. Instead of getting an alert box with a json with 26 outputs (one for each folder), I get 27. It even assigns a value to the 27th folder. In my directory there is no folder with the name: "27". Any idea why this happening?

1

There are 1 best solutions below

0
On BEST ANSWER

Let me phrase this as an answer:

For every iteration you are actually adding an extra record to the array because of the array_push()

With $noCoords[$number] = $x-2 you'll add index 1 through 26 and the line after you create an extra entry with $number + 1

So what happens (assume your folder 25 and 26 have 100 and 90 files respectively):

$index = 25:

$noCoords[25] = 98; // $noCoords[$number] = $x-2
$noCoords[26] = 100; // array_push($noCoords,$x);

$index = 26:

$noCoords[26] = 88; // $noCoords[$number] = $x-2
$noCoords[27] = 90; // array_push($noCoords,$x);