Remove Blank Entries From An Array With PHP

Monday, June 2, 2008 - 09:13

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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.

1
2
3
4
// 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).'
'; // print result of array_purge_empty() function echo ''.print_r(array_purge_empty($array),true).'';

This produces the following output.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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.

Category: 
philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter

Add new comment