Gus
Gus

Reputation: 943

Remove only associative array with all values empty

Is it possible to remove only the associative array who have all values empty?

Data source:

 Array
(
    [0] => Array
        (
            [name] => foo
            [phone] => 012345
            [email] => 
        )

    [1] => Array
        (
            [name] => bar
            [phone] => 
            [email] => yahoo.com
        )
    [2] => Array
        (
            [name] => 
            [phone] => 
            [email] => 
        )
)

Desired output:

Array
(
    [0] => Array
        (
            [name] => foo
            [phone] => 012345
            [email] => 
        )

    [1] => Array
        (
            [name] => bar
            [phone] => 
            [email] => yahoo.com
        )
)

I tried this, but unfortunately I will delete all empty values ​​of arrays

$_arr = array_filter(array_map('array_filter', $_arr));

Array
(
    [0] => Array
        (
            [name] => foo
            [phone] => 012345
        )

    [1] => Array
        (
            [name] => bar
            [email] => yahoo.com
        )
)

How could I do it? Thank You

Upvotes: 1

Views: 122

Answers (2)

Mihir Bhende
Mihir Bhende

Reputation: 9055

<?php 
$collection = array(
                    "0" => array
                        (
                            'name' => "foo",
                            'phone' => "012345",
                            'email' => ''
                        ),

                    "1" => array
                        (
                            'name' => "bar",
                            'phone' => '',
                            'email' => "yahoo.com",
                        ),
                    "2" => array
                        (
                            'name' => '',
                            'phone' => '',
                            'email' => ''
                        )
                );

foreach($collection as $key=> $entry){

    if(count(array_filter($entry)) == 0){
        unset($collection[$key]);
    }
}

print_r($collection);

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 78994

Maybe a slicker way, but:

$array = array_filter($array, function($a) { return array_filter($a); });

Since array_filter is using a true or false return to filter; the array_filter in the function is returning either an empty array evaluated as false, or a non-empty array evaluated as true, and the main array_filter is filtering based upon that.

Upvotes: 2

Related Questions