2

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

Liam Fell
  • 1,308
  • 3
  • 21
  • 39

3 Answers3

6

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;
swidmann
  • 2,787
  • 1
  • 18
  • 32
  • 1
    Thanks for that, that's a very useful way of filter in a loop – Liam Fell Nov 12 '15 at 10:39
  • 1
    While this is a good answer, please format it so that newcomers understand that the continue is within the if(), while the echo is not. – Bonatti Nov 12 '15 at 10:42
2

You can eliminate these directories with array_diff:

$dir = scandir($path);
$dir = array_diff($dir, array('.', '..'));
foreach($dir as $entry) {
    // ...
}
Tom Regner
  • 6,856
  • 4
  • 32
  • 47
1

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.

madsen
  • 422
  • 3
  • 9