Search code examples
phparraysarray-filter

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

Solution

  • 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