-1

How can I filter array and delete all empty elements. I need to remove empty elements from an array, including arrays in arrays.

From that array:

$array = [
    'ip' => '127.0.0.1',
    'user_agent' => 'dkdkdk',
    '_id' => 'fjjfjf',
    'user' => [
        'longName' => '', 
        'shortName' => '',
        'username' => [
            'a' => 'b',
            'c' => ''
            ]
    ],
    'dsd' => [
        'zz' => [
            'dd' => [
                'ff' => ''
                ]
            ]
        ]
    ],
    'dsddd' => '',
    'vcv' => null,
    'aavx' => 0
];

I want get:

$array = [
    'ip' => '127.0.0.1',
    'user_agent' => 'dkdkdk',
    '_id' => 'fjjfjf',
    'user' => [
        'username' => [
            'a' => 'b',
            ]
    ],
    'aavx' => 0
];

I try use array_filter but it remove only not array keys

KlodeMone
  • 1
  • 1
  • https://stackoverflow.com/a/6795671/1427878 - modify accordingly, so that the filtering happens by your specific criterion. – CBroe Mar 23 '20 at 14:41
  • (And please pay a bit more attention when showing example data. What you have currently shown, is not even syntactically valid.) – CBroe Mar 23 '20 at 14:53
  • Does this answer your question? [PHP - How to remove empty entries of an array recursively?](https://stackoverflow.com/questions/7696548/php-how-to-remove-empty-entries-of-an-array-recursively) – M. Volf Mar 23 '20 at 17:11

1 Answers1

0

To remove all empty arrays or keys, you will have to iterate recursively and pass value by reference to the subsequent recursive calls to make sure you edit the same copy of the subarray. Now, you can just have empty checks and unset them.

function removeEmptyArrays(&$array){
    foreach($array as $key => &$value){
        if(is_array($value)) removeEmptyArrays($value);
        if(is_array($value) && count($value) == 0 || is_null($value) || is_string($value) && strlen($value) == 0) unset($array[$key]);
    }
}

Demo: https://3v4l.org/XDJdD

nice_dev
  • 17,053
  • 2
  • 21
  • 35