views:

35

answers:

3

i wonder how i can transform exactly the following piece of code to scandir instead of readdir?

$path = 'files';

//shuffle files
$count = 0;
if ($handle = opendir($path)) {
    $retval = array();
    while (false !== ($file = readdir($handle))) {
        $ext = pathinfo($file, PATHINFO_EXTENSION);
        if ($file != '.' && $file != '..' && $file != '.DS_Store' &&
          $file != 'Thumbs.db') {
            $retval[$count] = $file;
            $count = $count + 1;
            } else {
            //no proper file
        }
    }
    closedir($handle);
}
shuffle($retval);
A: 

Not sure why you want to do that, here's a much more concise solution though:

$path = 'files';
$files = array();
foreach (new DirectoryIterator($path) as $fileInfo) {
    if($fileInfo->isDot() || $fileInfo->getFilename() == 'Thumbs.db') continue;
    $files[] = $fileInfo->getFilename();
}
shuffle($files);
seengee
+2  A: 

scandir returns, quoting :

Returns an array of filenames on success, or FALSE on failure.

Which means you'll get the full list of files in a directory -- and can then filter those, using either a custom-made loop with foreach, or some filtering function like array_filter.


Not tested, but I suppose something like this should to the trick :

$path = 'files';
if (($retval = scandir($path)) !== false) {
    $retval = array_filter($retval, 'filter_files');
    shuffle($retval);
}


function filter_files($file) {
    return ($file != '.' && $file != '..' && $file != '.DS_Store' && $file != 'Thumbs.db');
}

Basically, here :

  • First, you get the list of files, using scandir
  • Then, you filter out the ones you dn't want, using array_filter and a custom filtering function
    • Note : this custom filtering function could have been written using an anonymous function, with PHP >= 5.3
  • And, finally, you shuffle the resulting array.
Pascal MARTIN
A: 

To get started with such problems always consult the PHP manual and read the comments, it's always very helpful. It states that scandir returns an array, so you can walk through it with foreach.

In order to be able to delete some entries of the array, here's an example with for:

$exclude = array( ".", "..", ".DS_Store", "Thumbs.db" );
if( ($dir = scandir($path)) !== false ) {
    for( $i=0; $i<count($dir); $i++ ) {
        if( in_array($dir[$i], $exclude) )
            unset( $dir[$i] );
    }
}

$retval = array_values( $dir );

Also have a look at the SPL iterators PHP provides, especially RecursiveDirectoryIterator and DirectoryIterator.

svens