一个更好的方法来取消设置空变量?

问题描述:

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?

目前我正在检查$ _FILES数组是否为空以取消设置: p>

  if($ var ==='AP'&& empty($ _ FILES ['field_1'] ['name'])){
 unset($ _ FILES ['field_1']);  
 
} 
 if($ var ==='AP'&& empty($ _ FILES ['field_2'] ['name'])){
 unset($ _ FILES ['field_2'])  ; 
 
} 
 nif($ var ==='AP'&& empty($ _ FILES ['field_1'] ['name'])&& empty($ _ FILES ['field_2'] [  'name'])){
 unset($ _ FILES ['field_1']); 
 unset($ _ FILES ['field_2']); 
 
} 
  code>  pre> 
  
 

这适用于图片上传,当有少量图片可以上传时,它可以正常工作。 现在我将有15个上传字段,它们都是可选的。 是否有更好的方法来取消设置那些空的数组而不为每个可能的组合执行上述条件? p> div>

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);