2

I have array in which several child arrays exists. I want to remove those arrays which specifics values are empty.

Array ( 
[9] => Array ( [address_id] => 9 [firstname] => [lastname] =>  ) 
[10] => Array ( [address_id] => 10 [firstname] => the [lastname] => king  ) 
[11] => Array ( [address_id] => 11 [firstname] => the [lastname] => queen  ) 
)

You can see firstname and lastname is empty in [9] => Array(). So how can i remove those arrays which firstname has blank? I have tried array_filter() but didn't solve my issue.

the acc
  • 51
  • 5
  • Try using [array_map](http://php.net/manual/en/function.array-map.php) and recursively unset the cells which have an empty lastname or firstname ? – Answers_Seeker Jan 19 '16 at 16:12
  • Possible duplicate of [How to remove empty values from multidimensional array in PHP?](http://stackoverflow.com/questions/10214531/how-to-remove-empty-values-from-multidimensional-array-in-php) – Hardy Mathew Jan 19 '16 at 16:17
  • Did you give up or what? – AbraCadaver Jan 19 '16 at 19:37

3 Answers3

2

Try array_filter() with an anonymous function:

$array = array_filter($array, function($v) { return !empty($v['firstname']); });

For firstname AND lastname:

$array = array_filter($array,
                      function($v) {
                        return !empty($v['firstname']) && !empty($v['lastname']);
                      });

Keep in mind empty() is also 0, false and null, so for just an empty string you might want return $v['firstname'] !== ''; or something similar.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
0

Assuming parent array is named $parent, you want to loop through and check conditionally for two empty fields, then unset indexes that match.

foreach ($parent as $key -> $value){
    if ($value['lastname'] == "" AND $value['firstname'] == ""){
        // Names not set, remove from parent array
        unset($parent[$key]);
    }
}
Andrew Coder
  • 1,058
  • 7
  • 13
0

remove all the keys from nested arrays that contain no value, then remove all the empty nested arrays.

$postArr = array_map('array_filter', $postArr);
$postArr = array_filter( $postArr );
Hardy Mathew
  • 684
  • 1
  • 6
  • 22