PHP: remove empty array lines in a multidimensional array

I have this array:

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

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

How can I delete them?

I tried:

 $aryMain = array_filter($aryMain); 

But it does not work :(

Thanks a lot!

+6
source share
3 answers

To add an answer to Rikesh:

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

Pasting its code into another array_filter will get rid of all arrays.

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

Compared with:

 $aryMain = array_map('array_filter', $aryMain); Array ( [0] => Array ( [0] => hello [1] => bye ) [1] => Array ( ) [2] => Array ( ) ) 
+17
source

Use array_map along with array_filter,

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

Or just create an 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: this will delete elements containing '0' (i.e. a string with a zero digit). Just pass 'strlen' as the second parameter to save 0

+9
source

Apply array_filter() to the main array, and then again about the internal elements:

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

The internal array_filter() uses strlen() to determine if the element is empty; otherwise it will remove the '0' .

To determine the void of an array, you can also use array_reduce() :

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

Is it possible that this is more efficient, but it should save some memory :)

+2
source

Source: https://habr.com/ru/post/944949/


All Articles