WP-Mix

A fresh mix of code snippets and tutorials

PHP: Remove Empty File Data

This quick function does one simple thing. It removes empty file data from a PHP files array. As you may know, the structure of the $_FILES array is sort of backwards from what normally would be expected. Because of this, removing empty file data from the array requires some extra wrangling. So to make things easier you can use the following function to clean up your files array by removing any empty file data.

// Remove Empty File Data
// https://wp-mix.com/php-remove-empty-file-data/
function shapeSpace_remove_empty_file_data($files) {
	
	$unset = array();
	
	foreach ($files as $key => $value) {
		foreach ($value as $k => $v) {
			if ($key == 'tmp_name' && empty($v)) {
				$unset[] = $k;
			}
		}
	}
	
	if (!empty($unset)) {
		foreach ($unset as $index) {
			foreach ($files as $key => $value) {
				foreach ($value as $k => $v) {
					unset($files[$key][$index]);
				}
			}
		}
	}
	
	return $files;
	
}

Once this function is added to your script, you can use it by passing in your files array, for example:

<?php $files = shapeSpace_remove_empty_file_data($files); ?>

Cheers!

★ Pro Tip:

USP ProSAC Pro