1

I have an array where I do not know what the keys are called and I am trying to remove all the items from array where all of the sub keys are empty (wihout value).

My array could look like this. The second element [1] has empty values so I would like to remove it and only leave the first element [0].

Array
(
    [0] => Array
        (
            [Some key here] => 26542973
            [generated key] => John
            [who knows what key] => 10
        )

    [1] => Array
        (
            [Some key here] => 
            [generated key] => 
            [who knows what key] => 
        )

)

I tried using array filter but it did not remove the empty element. It left both of them in the array.

$filtered_array = array_filter($array);

I would like to have the end result look like this (empty element removed).

Array
(
    [0] => Array
        (
            [Some key here] => 26542973
            [generated key] => John
            [who knows what key] => 10
        )
)
Mohammad
  • 21,175
  • 15
  • 55
  • 84
Liga
  • 3,291
  • 5
  • 34
  • 59
  • 1
    So what should happen if only one of the sub elements are empty for example just `[Some key here]` – RiggsFolly Oct 31 '18 at 10:51
  • It should remove only if all sub elements are empty. I should update the question. – Liga Oct 31 '18 at 10:53
  • Have a look through https://stackoverflow.com/questions/9895130/recursively-remove-empty-elements-and-subarrays-from-a-multi-dimensional-array as it covers quite a few scenarios. – Nigel Ren Oct 31 '18 at 10:54

2 Answers2

4

Use array_map with array_filter.

$array = array(array('data1','data1'), array('data2','data2'), array('','')); 
$array = array_filter(array_map('array_filter', $array));
print_r($array);

DEMO

Dave
  • 3,073
  • 7
  • 20
  • 33
2

You can use array_filter() as shown in bottom. So you need to join items of inner array using implode() and check that result is empty or not.

$arr = array_filter($arr, function($val){
    return implode("", $val) != "";
});

Check result in demo

Mohammad
  • 21,175
  • 15
  • 55
  • 84