Possible Duplicate:
How do you loop through $_FILES array?
For some reason arrays really get to me. I can get there in the end, but this $_FILES array seems to be backwards to me.
I want to be able to loop through $_FILES like so:
foreach($_FILES as $file)
{
echo $file['name'] . "<br>";
echo $file['type'] . "<br>";
echo $file['size'] . "<br>";
echo $file['error'] . "<br>";
}
But obviously with the way its structured you cannot do that. So I have written the following:
echo "<pre>";
$x=0;
$file = array();
foreach($_FILES['attachment']['name'] as $data)
{ $file[$x]=array();
array_push($file[$x],$data); $x++;
}
$x=0;
foreach($_FILES['attachment']['type'] as $data)
{ array_push($file[$x],$data); $x++;}
$x=0;
foreach($_FILES['attachment']['tmp_name'] as $data)
{ array_push($file[$x],$data); $x++;}
$x=0;
foreach($_FILES['attachment']['error'] as $data)
{ array_push($file[$x],$data); $x++;}
$x=0;
foreach($_FILES['attachment']['size'] as $data)
{ array_push($file[$x],$data); $x++;}
var_dump($file);
echo "</pre>";
Which seems very long winded and rediculous but my mind is stuck at the moment as to how to loop through properly the different parts of this array to get it work and loop the way I want it to.
There must be a better way?
Please help!
If they all have the same length you can do it like this
for($i = 0; $i < count($_FILES['attachment']['name']); $i++)
{
echo $_FILES['attachment']['name'][$i] . "<br>";
echo $_FILES['attachment']['type'][$i] . "<br>";
echo $_FILES['attachment']['size'][$i] . "<br>";
echo $_FILES['attachment']['error'][$i] . "<br>";
}
From your code, i suppose your <form>
inputs look like this:
<input type="file" name="attachment[]">
<input type="file" name="attachment[]">
If you give unique names to the file fields you should get the $_FILES
structure you want:
<input type="file" name="attachment0">
<input type="file" name="attachment1">
results in something like this:
array(2) { 'attachment0' => array(5) { 'name' => string(8) "1528.jpg" 'type' => string(0) "" 'tmp_name' => string(0) "" 'error' => int(2) 'size' => int(0) } 'attachment1' => array(5) { 'name' => string(8) "1529.jpg" 'type' => string(0) "" 'tmp_name' => string(0) "" 'error' => int(2) 'size' => int(0) } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With