Liga
Liga

Reputation: 3439

Remove empty array elemnts from array without knowing keys

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

Upvotes: 1

Views: 80

Answers (2)

Mohammad
Mohammad

Reputation: 21489

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

Upvotes: 2

Dave
Dave

Reputation: 3091

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

Upvotes: 4

Related Questions