Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove empty associative array entries

I have an associative array: $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
        )
)

How can I remove all completely empty entries such as $csv_arr[2] but preserve partial entries such as $csv_arr[1]

I've tried $csv_arr = array_filter(array_map('array_filter', $csv_arr)); but this removes the empty element: $csv_arr[1]['Enfapro']

Thx

like image 969
Andy Gee Avatar asked Jul 29 '13 11:07

Andy Gee


Video Answer


1 Answers

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));
?>
like image 50
John V. Avatar answered Oct 12 '22 20:10

John V.