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);
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
.
$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 :
scandir
array_filter
and a custom filtering function
shuffle
the resulting array.