简体   繁体   中英

PHP: Using scandir bu excluding ../ ./ in the result

I'm using scandir and a foreach loop to display a list of files in a directory to the user. My code is below:

        $dir = scandir('/user1/caravans/public_html/wordpress/wp-content/uploads/wpallimport/files');

        foreach($dir as $directory)
{
        echo "<br/><input type='checkbox' name=\"File[]\" value='$directory'/>$directory<br>";
        }

The problem is the script also echos a "." and a ".." (without the speech marks), is there an elegant way to remove these? Short or a regular expression. Thanks

Just continue if the directory is . or .. I recommend to take a look at the control structures here

$dir = scandir('/user1/caravans/public_html/wordpress/wp-content/uploads/wpallimport/files');

foreach($dir as $directory) {
    if( $directory == '.' || $directory == '..' ) {
        // directory is . or ..
        // continue will directly move on with the next value in $directory
        continue;
    }

    echo "<br/><input type='checkbox' name=\"File[]\" value='$directory'/>$directory<br>";
}

Instead of this:

if( $directory == '.' || $directory == '..' ) {
    // directory is . or ..
    // continue will directly move on with the next value in $directory
    continue;
}

you can use a short version of it:

if( $directory == '.' || $directory == '..' ) continue;

You can eliminate these directories with array_diff :

$dir = scandir($path);
$dir = array_diff($dir, array('.', '..'));
foreach($dir as $entry) {
    // ...
}

Another solution, in addition to swidmann's answer, is to simply remove '.' and '..' before iterating over them.

Adapted from http://php.net/manual/en/function.scandir.php#107215

$path    = '/user1/caravans/public_html/wordpress/wp-content/uploads/wpallimport/files';
$exclude = ['.', '..'];
$dir     = array_diff(scandir($path), $exclude);

foreach ($dir as $directory) {
    // ...
}

That way you can also easily add other directories and files to the excluded list should the need arise in the future.

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