2

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" 
}
1
  • agree with @HankyPankyㇱ Commented May 6, 2013 at 7:04

4 Answers 4

4

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

You can get rid of it by using below code

$files = array_diff(scandir($dir), array('..', '.'));
Sign up to request clarification or add additional context in comments.

Comments

0

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);
}
?>

Comments

0

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

1 Comment

Thanks, that explains a lot
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.