Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through $_FILES?

Tags:

html

file

php

I want to add loop around $_FILES[] array. I tried $count= count($_FILES['files'][name]) and then add loop around it for($i=0; $i<=$count; $i++), but it is not giving me desired output.

I want add to loop only from the files that the User is uploading, Right now it is counting all of the 'files' available in the form.

Kindly tell me a way to count only the uploaded files and loop through them.

like image 458
Taha Kirmani Avatar asked Dec 25 '22 22:12

Taha Kirmani


2 Answers

Loop ever the $_FILES array and use the ['name'] inside the iteration:

$count = count($_FILES['files'])
for($i=0; $i<=$count; $i++) {
  if ($_FILES['files'][$i]['size'])
    echo $_FILES['files'][$i]['name']."\n";
}

Even easier is to use a foreach loop:

foreach($_FILES['files'] as $file) {
  if($file['size'])
    echo $file['name']."\n";
}
like image 93
arkascha Avatar answered Dec 29 '22 11:12

arkascha


You can use array_filter for that. You filter the array to just get the inputs with uploaded files in them.

$uploaded_files = array_filter($_FILES['files'], function($file){ 
    return $file['size']; 
});

print count($uploaded_files);

foreach($uploaded_files as $file)
{
    //code
}
like image 39
Oskar Hane Avatar answered Dec 29 '22 12:12

Oskar Hane