PHP 数组返回的计数超出了应有的数量?

标签 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 结果

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/

相关文章:

python - 计算 pandas DataFrame 中的子词频率

javascript - 运行 R 脚本时网站加载时间较长

php - 如何从mysql数据创建图表? (使用谷歌可视化 API)

java - 数组内的数组 - Java

php - 从 paypal 数组获取状态

mysql - SQL 计算多列

php - 在 PHP 中动态填充静态变量

php - 我如何对下表进行排序并获得前 5-5 条记录,前 20-20 条记录?

python - 索引错误: index is out of bounds for axis 0 with size

python - 将列转换为包含列值计数的列标题