Remove Blank Entries From An Array With PHP

2nd June 2008 - 2 minutes read time

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

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 '<pre>'.print_r($array,true).'</pre>';
  5. // print result of array_purge_empty() function
  6. echo '<pre>'.print_r(array_purge_empty($array),true).'</pre>';

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.