How to find the first 5 files in a directory with PHP?

How can I list the first 5 files or directories in a directory sorted alphabetically using PHP?

+3
source share
3 answers

Usage scandir():

array_slice(array_filter(scandir('/path/to/dir/'), 'is_file'), 0, 5);

array_filter()Together with the function callback is_file(), it ensures that we simply process the files without having to write a loop, we don’t even need to take care of .and .., since they are directories.


Or usingglob() - it will not match file names, for example .htaccess:

array_slice(glob('/path/to/dir/*.*'), 0, 5);

glob() + array_filter() - , .htaccess:

array_slice(array_filter(glob('/path/to/dir/*'), 'is_file'), 0, 5);
+17

( inode), readdir - .

, , , scandir . :

$firstfive = array_slice(scandir("."), 2, 5);

, , scandir, ".". "..".

+1

, scandir, - . scandir , :

$items = scandir('/path/to/dir');
$files = array();
for($i = 0, $i < 5 && $i < count($items); $i++) {
    $fn = '/path/to/dir/' . $items[$i];
    if(is_file($fn)) {
        $files[] = $fn;
    }
}
+1

Source: https://habr.com/ru/post/1729475/


All Articles