user782104
user782104

Reputation: 13555

How to get filtered file name list using scandir in PHP?

I would like to get all files that has '_img' and PDF type in a folder

Instead of using

$fileArray = scandir($dir);
foreach ($fileArray as $file) {
    if (preg_match("_img",$file) && pathinfo($file, PATHINFO_EXTENSION) == 'pdf'){
        $filteredArray[] = $file;
    }
}

Are there any short cut or it is the best way? Thanks

Upvotes: 4

Views: 8767

Answers (2)

Robert
Robert

Reputation: 20286

Use php glob() function

The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells

<?php 
  $filteredArray = array();
  foreach (glob($dir."/*_img.pdf") as $filename)
     $filteredArray[] = $filename;
?>

There is also fnmatch() function which matches filename against a pattern

The last solution is to use DirectoryIterator with FilterIterator

Upvotes: 3

DjimOnDev
DjimOnDev

Reputation: 399

To me this works fine. you walk into you directory and store this to an array.

At this level, an optimisation is not needed. you'll win peanuts losting time to optimize this.

Upvotes: 2

Related Questions