PHP的数组返回的数量应该超过应有的数量?

时间:2013-05-06 07:01:46

标签: php arrays count sizeof

这是我的代码:

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

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

数组的计数在空数组上返回值为2,我为隐藏文件,零重新获取。 那么是什么导致这个? 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" 
}

4 个答案:

答案 0 :(得分:4)

因为你的数组包含'。' &安培; '..'两个文件名。

您可以使用以下代码

来摆脱它
$files = array_diff(scandir($dir), array('..', '.'));

答案 1 :(得分:0)

您应首先检查scandir的返回值。看看$files是否真的是一个数组?

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

答案 2 :(得分:0)

这是scandir()的正常行为,也是正确的。

这是因为每个目录都包含两个逻辑条目

1)“。”参考当前目录 2)“..对父目录的引用。

所以对于空目录,你也会得到清单2的东西。

请参阅:PHP scandir() Function

答案 3 :(得分:0)

问题是scandir()也返回“。”和“..”指的是父目录。如果你var_dump($ files)你会看到我在说什么。

相关问题