Reputation: 2301
I've got an array I use in a FormValidator
class, but at some point I end up with an array sort of like the following. But I would like to remove all empty arrays from that array so that in my validation it's not gonna check for values inside the empty array, which is inefficient.
Is there a function to remove empty arrays from multidimensional arrays?
I know about array_filter()
but that seems to only work with array element values.
array(2)
{
["recaptcha_response_field"]=>
array(0) {
}
["terms"]=>
array(0) {
}
}
Upvotes: 3
Views: 14028
Reputation: 1166
try this- This will remove empty arrays as well inside array!
$array['recaptcha_response_field'] = array(
'name'=>'name1',
'email'=>'email1',
'empty'=>''
);
$array['terms'] = array(
'name'=>'name2',
'email'=>'email2',
'empty'=>''
);
$array['terms2'] = array();
$array= array_filter(array_map('array_filter', $array));
print_r($array);
OUTPUT-Array
(
[recaptcha_response_field] => Array
(
[name] => name1
[email] => email1
)
[terms] => Array
(
[name] => name2
[email] => email2
)
)
Upvotes: 15
Reputation: 3078
Use array_filter function to remove an element from array. To identify the null elements fire recursive loop. hope it will work !
Upvotes: 0
Reputation: 160
$array = array(array('foo','bar'), array('hi',''), array('',''), array('','hello'));
$array = array_filter(array_map('array_filter', $array));
print_r($array);
will show :
Array ( [0] => Array ( [0] => foo [1] => bar ) [1] => Array ( [0] => hi ) [3] => Array ( [1] => hello ) )
Upvotes: 2
Reputation: 68486
Use a simple foreach
with array_filter
and count
as the call-back function.
foreach($arr as $k=>&$arr)
{
array_filter($arr,'count');
}
print_r($arr);
Upvotes: 1