搜索文件或目录时,跳过PHP的scandir函数的第一个(。)和第二个值(..)是否保存?

我实际上已经问了我好几年了: 跳过由提取的数组的第一个和第二个值是否省钱scandir?


现在,我正在遍历一个scandir(或多或少)这样的数组:


for ( $scan = scandir('path/to/dir/'), $i = 0, $c = count( $scan ); $i < $c; ++$i )

{

    if ( $scan[ $i ][ 0 ] != '.' )

    {

        // $scan[ $i ] is file name or dir name

    }

}

这也可以很好地工作,但是如果$scan[ 0 ][ 0 ]一直.和$scan[ 1 ][ 0 ]一直都似乎是多余的..。


这样可以省去跳过第一个和第二个值:


for ( $scan = scandir('path/to/dir/'), $i = 2/* starting with 2 instead of 0 */, $c = count( $scan ); $i < $c; ++$i )

{

    // $scan[ $i ] is file name or dir name

}

当我var_dump一个scandir我总是得到这样的结构:


var_dump( scandir('path/to/dir/') );

array(

    0 => '.',  // is this the case for each

    1 => '..', // and every environment

    2 => 'filename.ext',

    [...]

)

但是我主要在自己的服务器环境中工作,并且没有看到太多不同的服务器环境。因此,我可以确定在每种环境(操作系统,PHP版本等)中,我都会找到一种scandir与上面类似的结构吗?


慕后森
浏览 172回答 1
1回答

紫衣仙女

不,你不能安全地假设.和..将首先返回。默认情况下,来自的结果scandir()将按字母顺序返回,就像结果已传递给一样sort()。但是,有些字符会在上方排序.-例如,一个名为的文件!README将在之前返回.。如果要跳过这些条目,请明确检查它们,例如foreach (scandir("path/to/dir") as $file) {&nbsp; &nbsp; if ($file === "." || $file === "..")&nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; // do stuff with $file}
打开App,查看更多内容
随时随地看视频慕课网APP