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
        )
)
3
  • 1
    So what should happen if only one of the sub elements are empty for example just [Some key here] Commented Oct 31, 2018 at 10:51
  • It should remove only if all sub elements are empty. I should update the question. Commented Oct 31, 2018 at 10:53
  • Have a look through stackoverflow.com/questions/9895130/… as it covers quite a few scenarios. Commented Oct 31, 2018 at 10:54

2 Answers 2

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

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

1 Comment

If you have array('data3','') this will remove the empty element, is that what is needed?
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

4 Comments

It left all of the empty ones and removed the ones with values (the opposite effect)
@Liga Bug fixed :)
Does it require all sub items to be empty or just one?
@Liga All as you said.

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.