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

2 answers

  • answered 2017-11-15 00:35 ourmandave

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

  • answered 2017-11-15 10:09 sintakonte

    a possible option would be to use a DirectoryIterator

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