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_remove_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
)
Recent Comments