这是我的代码:
$dir = "img/";
$files = scandir($dir);
for ($i=0; $i <= count($files); $i++) {
echo $files[$i]."<br/>";
}
echo count($files);
数组计数在空数组上返回值 2,我检查了隐藏文件,结果为零。 那么什么会导致这种情况呢? var_dump 结果
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"
}
最佳答案
这是因为你的数组包含“.” & '..' 两个文件名。
您可以使用下面的代码摆脱它
$files = array_diff(scandir($dir), array('..', '.'));
关于PHP 数组返回的计数超出了应有的数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16393625/