How to remove empty associative array entries

This one example is tested and it's working:

   $csv_arr = [
           0 => [
               'Enfalac' => 'alpha linolenic acid 300 mg',
               'Enfapro' => 'alpha linolenic acid 200 mg',
           ],

           1 => [
               'Enfalac' => 'arachidonic acid 170 mg',
               'Enfapro' => '',
           ],

           2 => [
               'Enfalac' => '',
               'Enfapro' => '',
           ],

           3 => [

               'Enfalac' => 'calcium 410 mg',
               'Enfapro' => 'calcium 550 mg',
           ],
       ];

       var_dump(array_filter(array_map('array_filter', $csv_arr)));



In your case it might be even easier. I recently had the same issue. Just use

$csv_arr = array_filter($csv_arr, 'array_filter');

array_filter() removes elements from the array which bool convert to false. This includes - for example - each of [], null, '', 0, false.

What it does

  1. The first array_filter() takes each of the sub-arrays and throws it in the second array_filter().
  2. The second array_filter() removes every false element and returns the rest. Its important to notice that the returned array will become empty if every element converts to false.
  3. The first array_filter() takes the result from the second and checks against false. So, in case an empty array is returned the sub-array will be removed from the array.

To prove the case I took the example from John V. and used the single array_filter() line:

<?php
$csv_arr = array(
    0 => array(
            'Enfalac' => 'alpha linolenic acid 300 mg',
            'Enfapro' => 'alpha linolenic acid 200 mg'
        ),

    1 =>  array(
            'Enfalac' => 'arachidonic acid 170 mg',
            'Enfapro' => ''
        ),

    2 =>  array(
            'Enfalac' => '',
            'Enfapro' => ''
        ),

    3 =>  array(

            'Enfalac' => 'calcium 410 mg',
            'Enfapro' => 'calcium 550 mg'
        )
);
print_r(array_filter($csv_arr, 'array_filter'));

Try this, a little weird, but :

array_filter($csv_arr, function($v){return array_filter($v) == array();});

Completely untested and I don't remember if this is the proper syntax or not for closures, but it could work.

Edit (tested and working):

<?php
$csv_arr = array(
    0 => array(
            'Enfalac' => 'alpha linolenic acid 300 mg',
            'Enfapro' => 'alpha linolenic acid 200 mg'
        ),

    1 =>  array(
            'Enfalac' => 'arachidonic acid 170 mg',
            'Enfapro' => ''
        ),

    2 =>  array(
            'Enfalac' => '',
            'Enfapro' => ''
        ),

    3 =>  array(

            'Enfalac' => 'calcium 410 mg',
            'Enfapro' => 'calcium 550 mg'
        )
);
$c = function($v){
    return array_filter($v) != array();
};
var_dump(array_filter($csv_arr, $c));
?>