newbie newbie - 1 month ago 6
PHP Question

How can I iterate PHP $_FILES array?

This might be stupid question, but PHPs array $_FILES has very odd format, which I have never used before. Can somebody tell me how can I iterate this array in sane way ? I have used to iterate objects or object like arrays, but this format is very odd for me. Is there any way to iterate this array like object array?

( [attachments] =>
Array (
[name] => Array (
[0] => test1.png
[1] => test2.png
)
[type] => Array (
[0] => image/png
[1] => image/png
)
[tmp_name] => Array (
[0] => /tmp/phpmFkEUe
[1] => /tmp/phpbLtZRw
)
[error] => Array (
[0] => 0
[1] => 0
)
[size] => Array (
[0] => 9855
[1] => 3002
)
)
)

Answer

Wow, that indeed is odd, are you using <input type="file" name="attachments[]" /> in your markup? If you could afford to change those using unique name=, you won't have that odd format...

To directly answer your question, try:

$len = count($_FILES['attachments']['name']);

for($i = 0; $i < $len; $i++) {
   $fileSize = $_FILES['attachments']['size'][$i];
   // change size to whatever key you need - error, tmp_name etc
}
Comments