Search code examples
phpreaddirscandir

PHP: readdir to scandir?


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);

Solution

  • 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.