I would like to handle the multiple file uploads $_FILES in an array like this
foreach ($_FILES as $file) {
// do stuff...
// $file['name'] and as such
}
However the array seems something like this
Array (
[name] => Array (
[0] => 2010年10月04日_205047.jpg
[1] =>
[2] =>
)
[type] => Array (
[0] => image/jpeg
[1] =>
[2] =>
)
[tmp_name] => Array (
[0] => E:\localhost\tmp\php118.tmp
[1] =>
[2] =>
)
[error] => Array (
[0] => 0
[1] => 4
[2] => 4
)
[size] => Array (
[0] => 92127
[1] => 0
[2] => 0
)
)
How should I make it into the array of the format that I want ?
Thanks
asked Nov 17, 2010 at 10:19
Atif
10.9k22 gold badges68 silver badges97 bronze badges
-
Here is an example of how to do it that I wrote to similar question.Danijel– Danijel2013年05月08日 06:31:26 +00:00Commented May 8, 2013 at 6:31
4 Answers 4
This is kludgey, but
$_MYFILES = array();
foreach(array_keys($_FILES['name']) as $i) { // loop over 0,1,2,3 etc...
foreach(array_keys($_FILES) as $j) { // loop over 'name', 'size', 'error', etc...
$_MYFILES[$i][$j] = $_FILES[$j][$i]; // "swap" keys and copy over original array values
}
}
answered Nov 17, 2010 at 10:30
Marc B
362k44 gold badges433 silver badges508 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Atif
I think creating keys manually will take less resources compared to using array_keys since its always the same ?
Marc B
True, but this is PHP... no guarantees that a key won't be renamed, or new ones added, etc... later on. Not likely, but not impossible. The inner array_keys call could be done once and cached in a var before the first foreach loop, though.
Atif
I completely agree to it .. Thanks Marc
why don't you want to declare new array var and to fill it in desirable format? eg
$myarr = array();
foreach ($_FILES as $file) {
$myarr[] = array($file['name'][0], $file['type'][0], $file['tmp_name'][0], $file['size'][0]);
}
answered Nov 17, 2010 at 10:24
heximal
10.5k5 gold badges49 silver badges73 bronze badges
this worked for me
$files = array();
for($i =0;$_FILES['name'][$i] != NULL;$i++){
$files[] = array($_FILES['name'][$i], $_FILES['type'][$i], $_FILES['tmp_name'][$i], $_FILES['size'][$i]);
}
Comments
foreach ($_FILES['photo']['name'] as $key => $value){
$photo[$key]['name'] = $value;
}
foreach ($_FILES['photo']['type'] as $key => $value) {
$photo[$key]['type'] = $value;
}
foreach ($_FILES['photo']['tmp_name'] as $key => $value) {
$photo[$key]['tmp_name'] = $value;
}
foreach ($_FILES['photo']['error'] as $key => $value) {
$photo[$key]['error'] = $value;
}
foreach ($_FILES['photo']['size'] as $key => $value) {
$photo[$key]['size'] = $value;
}
if ($photo[0]['error'] == 4)
$photo = [];
echo '<pre>';
print_r($photo);
echo '</pre>';
Comments
lang-php