简体   繁体   中英

scandir returns [0] =>. and [1]=>.. in array

I have a simple PHP script with this snippet of code:

$files  = scandir($dir);    
print_r($files);

And noticed in my array i have:

    [0] => .
    [1] => ..
    [2] => assets.php
    [3] => loader.php

Is this a bug on my server or is it expected behavior, what are they? And if it's the latter is there any way to exclude them from the scan? As I wish to only get script files that I made from the directory and nothing else. Is there any way to exclude them from the scan?

No it isn't a bug.... . is the current directory, .. the parent directory

See the PHP Docs

The user-contributed notes show one way of excluding them:

$directory = '/path/to/my/directory';
$scanned_directory = array_diff(scandir($directory), array('..', '.'));

If you use other options besides scandir, such as SPL's DirectoryIterator, there's options to exclude them (such as combining it with a RegexIterator), or to test for them as you're iterating:

$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if (!$fileinfo->isDot()) {
        echo $fileinfo->getFilename() . "\n";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM