Remove Blank Entries From An Array With PHP

If you have an array that you want to remove any null data items from then you can use the following function. It will create a new array and only copy across items from the existing array if they contain a value. If the value is an array the function calls itself and makes sure that the returned array contains something before adding it to the new array.

function array_purge_empty($arr) {
 $newarr = array();
 foreach ($arr as $key => $val) {
  if (is_array($val)) {
   $val = array_purge_empty($val);
   // does the result array contain anything?
   if (count($val) != 0) {
    $newarr[$key] = $val;
   }
  } else {
   if (trim($val) != "") {
    $newarr[$key] = $val;
   }
  }
 }
 return $newarr;
}

Here is an example of the function in action.

// create array with some null items in it.
$array = array('a','b'=>'',3,0,' ',NULL,'',array(),array(1),4);
// print array 
echo '<pre>'.print_r($array,true).'</pre>';
// print result of array_purge_empty() function
echo '<pre>'.print_r(array_purge_empty($array),true).'</pre>';

This produces the following output.

Array
(
 [0] => a
 [b] =>
 [1] => 3
 [2] => 0
 [3] =>
 [4] =>
 [5] =>
 [6] => Array
  (
  )
 
 [7] => Array
  (
   [0] => 1
  )
 
 [8] => 4
)
 
Array
(
 [0] => a
 [1] => 3
 [2] => 0
 [7] => Array
  (
   [0] => 1
  )
 
 [8] => 4
)

Of course a simpler solution might be to use the PHP function array_filter(), which will remove any false entries. Additionally, if this function doesn't quite get all of the entries you wanted to catch you can include a function callback as the second parameter, which will allow you to refine the filtering done on the array. However, the array_filter() function is not recursive so I created the above function to provide a recursive array filtering function.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
4 + 6 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.