问题
I have a script where users can upload multiple files (max. 8). The HTML is generated by a piece of PHP:
$max_no_img=8;
for($i=1; $i<=$max_no_img; $i++){
<div class='photo photo$i'>
<div class='new_label'>
Foto $i:
</div>
<div class='new_input'>
<input type='file' name='images[]' />
</div>
</div>";
}
So the array images[] consists of 8 values. However, every time a user submit it's form, the form is generating an Array of 8 items and by so, inserting 8 values in the database (whether they are empty or not).
So I would like to unset the empty values, copy the files to my folders and insert the link into my database. But here is the part where the errors happen.
The array of $_FILES consists of 4 things. name, tmp_name, error and size. How do I get it so a complete item (let's say images[0]) will be unset from the array so I can continue with the items which actually carry a value.
I tried this, but with no results...
unset($_FILES['images'][0])
and
unset($_FILES['images']['name'][0])
unset($_FILES['images']['tmp_name'][0])
unset($_FILES['images']['error'][0])
unset($_FILES['images']['size'][0])
Any advice how to unset a value from a $_FILES-arry?
回答1:
You can just ignore them instead of processing or unsetting any items:
if (!empty($_FILES['images'])) {
for ($i = 0; $i < count($_FILES['images']['name']); $i++) {
if (empty($_FILES['images']['name'][$i])) {
// This item is empty
echo "Item $i references an empty field.\n";
continue;
}
echo "Item $i is a valid file.\n";
}
}
回答2:
You do not actually need to unset any items. Simply skip over the items that don't correspond to an uploaded file:
for($i=1; $i <= $max_no_img; $i++) {
if(empty($_FILES['images']['name'][$i])) {
continue; // that's all it takes
}
}
来源:https://stackoverflow.com/questions/8552390/unset-item-from-array-files-upload