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) { foreach ($arr as $key => $val) { $val = array_purge_empty($val); // does the result array contain anything? $newarr[$key] = $val; } } else { $newarr[$key] = $val; } } } return $newarr; }
Here is an example of the function in action.
// create array with some null items in it. // print array // print result of array_purge_empty() function
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.
0 comments:
Post a Comment