Raimonds
Raimonds

Reputation: 537

PHP count of array returns more than it should?

This is my code:

$dir = "img/";
$files = scandir($dir);

for ($i=0; $i <= count($files); $i++) { 
    echo $files[$i]."<br/>";
}
echo count($files);

count of array returns value of 2 on empty array, I cheched for hidden files, zero resault. So what can cause this? var_dump resault

array(7) { 
[0]=> string(1) "." 
[1]=> string(2) ".." 
[2]=> string(8) "img1.gif" 
[3]=> string(8) "img2.gif" 
[4]=> string(8) "img3.jpg" 
[5]=> string(8) "img4.png" 
[6]=> string(8) "img5.png" 
}

Upvotes: 2

Views: 145

Answers (4)

Guillermo
Guillermo

Reputation: 16

The problem is that scandir() also return "." and ".." referring to the parent directory. If you var_dump($files) you will see what i am talking about.

Upvotes: 0

CRDave
CRDave

Reputation: 9285

This is normal behaviour of scandir() and also true.

This because every directory contain two logical entry

1) "." reference to current directory.
2) ".. reference to parent directory.

So for empty directory also u will get at list 2 thing.

See : PHP scandir() Function

Upvotes: 0

Sudz
Sudz

Reputation: 4308

Its because your array contain '.' & '..' two file names.

You can get rid of it by using below code

$files = array_diff(scandir($dir), array('..', '.'));

Upvotes: 4

Hanky Panky
Hanky Panky

Reputation: 46900

You should be checking for return value of scandir first. See if $files is really an array?

<?php
$dir = "t";
$files = scandir($dir);
if(is_array($files))
{
for ($i=0; $i <= count($files); $i++) { 
    echo $files[$i]."<br/>";
}
echo count($files);
}
?>

Upvotes: 0

Related Questions