7

I am getting an array of filenames from a folder like this...

$files = File::allFiles('myfolder/');

But the resulting array contains pathname as well.

Is there a way of just getting an array of filenames? Or do I need to process each array item and extract the filename from it?

3 Answers 3

18

There is an another way of getting file name:

public function index() {

    $filesInFolder = \File::files('folder');     
    foreach($filesInFolder as $path) { 
          $file = pathinfo($path);
          echo $file['filename'] ;
     } 
} 

The pathinfo will gives you the output:

{ "dirname":"file_path", "basename":"file_name.file_extension", "extension":"file_extension", "filename":"file_name" }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, great alternative
3

hope it helps:

public function parse() {
    $fileNames = [];
    $path = public_path('other');
    $files = \File::allFiles($path);

    foreach($files as $file) {
        array_push($fileNames, pathinfo($file)['filename']);
    }

    dd($fileNames);
}

Comments

0

try the laravel Storage api:

use Illuminate\Support\Facades\Storage;

//...

$files = Storage::disk('diskName')->allFiles('folderName');
$fileNames = array_map(function($file){
    return basename($file); // remove the folder name
}, $files);
          


Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.