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!

1
  • 2
    Why not just skip those empty lines in the first place? Commented May 14, 2013 at 7:03

3 Answers 3

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

)
1
  • @MiguelMas Keep in mind that strings like '0' will get removed as well in this way. Commented May 14, 2013 at 7:17
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

1
  • 1
    Upvoted because of strlen tip! Commented Jan 31, 2017 at 4:35
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 :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.