Bart Az.
Bart Az.

Reputation: 1646

Codeigniter list only files non-recursively

I'd like to list the names of files from a specific location, without names of the subdirectories and files they may contain.

I've used CI's directory_map function with a success, but had to make a small workaround to get rid of the folder names in not quite a neat way:

$files = directory_map('src/img/example/', 1);

foreach($files as $i => $file) {
    if(strpos($file, '\\') !== false) {
        unset($files[$i]);
    }
}

I'm sure there has to be a way easier and better solution, but had no luck finding it

Upvotes: 0

Views: 245

Answers (2)

Atural
Atural

Reputation: 5439

a possible option would be to use a DirectoryIterator

$arrFiles = [];

foreach (new DirectoryIterator('src/img/example/') as $objFile) 
{
    if($objFile->isFile()) $arrFiles[] = $objFile->getFilename();
}

Upvotes: 0

ourmandave
ourmandave

Reputation: 1585

You can get an array of filenames in a one-liner, using scandir()

http://php.net/manual/en/function.scandir.php

Here's an example that does an array_diff() to remove the "." and ".." directories.

 $files = array_diff(scandir('src/img/example'), array('..', '.'));

You can also use array_filter().

$files = array_filter(scandir('src/img/example'), function($item) {
  return !is_dir('directory/' . $item);
});

Upvotes: 1

Related Questions