7

I have this array:

$aryMain = array(array('hello','bye'), array('',''),array('','')); 

It is formed by reading a csv file and the array('','') are the empty rows at the end of the file.

How can I remove them?

I've tried:

$aryMain = array_filter($aryMain);  

But it is not working :(

Thanks a lot!

Miguel Mas
  • 547
  • 2
  • 6
  • 23

3 Answers3

18

To add to Rikesh's answer:

<?php
$aryMain = array(array('hello','bye'), array('',''),array('','')); 
$aryMain = array_filter(array_map('array_filter', $aryMain));
print_r($aryMain);

?>

Sticking his code into another array_filter will get rid of the entire arrays themselves.

Array
(
    [0] => Array
        (
            [0] => hello
            [1] => bye
        )

)

Compared to:

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

Array
(
    [0] => Array
        (
            [0] => hello
            [1] => bye
        )

    [1] => Array
        (
        )

    [2] => Array
        (
        )

)
10

Use array_map along with array_filter,

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

Or just create a array_filter_recursive function

function array_filter_recursive($input) 
{ 
   foreach ($input as &$value) 
    { 
      if (is_array($value)) 
      { 
         $value = array_filter_recursive($value); 
      } 
   }     
   return array_filter($input); 
} 

DEMO.

Note: that this will remove items comprising '0' (i.e. string with a numeral zero). Just pass 'strlen' as a second parameter to keep 0

Rikesh
  • 26,156
  • 14
  • 79
  • 87
2

Apply array_filter() on the main array and then once more on the inner elements:

$aryMain = array_filter($aryMain, function($item) {
    return array_filter($item, 'strlen');
});

The inner array_filter() specifically uses strlen() to determine whether the element is empty; otherwise it would remove '0' as well.

To determine the emptiness of an array you could also use array_reduce():

array_filter($aryMain, function($item) {
    return array_reduce($item, function(&$res, $item) {
        return $res + strlen($item);
    }, 0);
});

Whether that's more efficient is arguable, but it should save some memory :)

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309