3

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) {
  }
}

4 Answers 4

15

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
        )

)
Sign up to request clarification or add additional context in comments.

Comments

2
$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 ) )

Comments

1

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);

Working Demo

Comments

0

Use array_filter function to remove an element from array. To identify the null elements fire recursive loop. hope it will work !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.