nikki
nikki

Reputation: 373

how to delete an empty array from multidimensional array in php

i need a function to delete an array which include an empty element from multidimensional array in php suppose following is my array here i need to find out and delete array[1] and array[2] since element empty has no value.

$array[] = array(
   'name'=>'name1',
   'email'=>'email1',
   'empty'=>'NOT_EMPTY'
);
$array[] = array(
   'name'=>'name2',
   'email'=>'email2',
   'empty'=>''
);
$array[] = array(
   'name'=>'',
   'email'=>'',
   'empty'=>''
);

when i do

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

print_r($array);

i got the result

Array
(
    [0] => Array
        (
            [name] => name1
            [email] => email1
            [empty]=> NOT_EMPTY
        )

    [1] => Array
        (
            [name] => name2
            [email] => email2
        )

    [2] => Array
        (
        )

) 

BUT EXPECTED RESULT

Array
(

    [0] => Array
        (
            [name] => name2
            [email] => email2
            [empty]=> NOT_EMPTY
        )

)

Upvotes: 0

Views: 158

Answers (1)

gwillie
gwillie

Reputation: 1899

array_filter() on its own only unsets values that equate to false, not the entire array. you will need to loop, and if any array has missing element, then unset array, like:

foreach($array as $key => $a){
  if(count(array_filter($a)) < count($a)){
    unset($array[$key]);
  }
}

there probably is a better way, i'm just simple

Upvotes: 1

Related Questions