Remove Blank Entries From An Array With PHP

2nd June 2008

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. function array_purge_empty($arr)
  2. {
  3. $newarr = array();
  4. foreach ($arr as $key => $val) {
  5. if (is_array($val)) {
  6. $val = array_purge_empty($val);
  7. // does the result array contain anything?
  8. if (count($val) != 0) {
  9. $newarr[$key] = $val;
  10. }
  11. } else {
  12. if (trim($val) != ") {
  13. $newarr[$key] = $val;
  14. }
  15. }
  16. }
  17. return $newarr;
  18. }

Here is an example of the function in action.

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

This produces the following output.

  1. Array
  2. (
  3. [0] => a
  4. [b] =>
  5. [1] => 3
  6. [2] => 0
  7. [3] =>
  8. [4] =>
  9. [5] =>
  10. [6] => Array
  11. (
  12. )
  13.  
  14. [7] => Array
  15. (
  16. [0] => 1
  17. )
  18.  
  19. [8] => 4
  20. )
  21.  
  22. Array
  23. (
  24. [0] => a
  25. [1] => 3
  26. [2] => 0
  27. [7] => Array
  28. (
  29. [0] => 1
  30. )
  31.  
  32. [8] => 4
  33. )

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.