Currently I am checking if the $_FILES array is empty to unset like so:
if ($var === 'AP' && empty($_FILES['field_1']['name'])) {
unset($_FILES['field_1']);
}
if ($var === 'AP' && empty($_FILES['field_2']['name'])) {
unset($_FILES['field_2']);
}
if ($var === 'AP' && empty($_FILES['field_1']['name']) && empty($_FILES['field_2']['name'])) {
unset($_FILES['field_1']);
unset($_FILES['field_2']);
}
This is for image uploads, it works when there are a small amount of images that can be uploaded. Now I'm going to have 15 upload fields with them all being optional. Is there a better way to unset those arrays that are empty without doing conditionals like above for each and every possible combination?
Instead of unsetting the ones that are empty, why not set the ones that are set? (This is good practice, since you may want to perform some validation action on the ones that are set)
$clean = array();
foreach($_FILE as $fileKey => $fileValue){
if($fileValue) {
$clean[$fileKey] = $fileValue;
}
// if you really want to unset it :
else{
unset($_FILE[$fileKey]);
}
}
for ($x = 0; $x < 15; $x++) {
if ($var === 'AP' && empty($_FILES[$x]['name'])) {
unset($_FILES[$x]);
}
}
Should do the trick. (Could use a check to make sure elements are set and some cleanup, but you get the idea)
It will actually be $_FILES['name'][0]
not $_FILES[0]['name']
,etc so just remove the empties:
$_FILES['name'] = array_filter($_FILES['name']);
Then just use $_FILES['name']
as the array to loop over and the keys will still be the same as the other arrays.
You can use array_filter
to remove empty elements:
$emptyRemoved = array_filter($linksArray);
If you have (int) 0
in your array, you may use the following:
$emptyRemoved = remove_empty($linksArray);
function remove_empty($array) {
return array_filter($array, '_remove_empty_internal');
}
function _remove_empty_internal($value) {
return !empty($value) || $value === 0;
}
EDIT: Maybe your elements are not empty per say but contain one or more spaces... You can use the following before using array_filter
$trimmedArray = array_map('trim', $linksArray);