-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

3
  • stackoverflow.com/a/6795671/1427878 - modify accordingly, so that the filtering happens by your specific criterion. Commented Mar 23, 2020 at 14:41
  • (And please pay a bit more attention when showing example data. What you have currently shown, is not even syntactically valid.) Commented Mar 23, 2020 at 14:53
  • Does this answer your question? PHP - How to remove empty entries of an array recursively? Commented Mar 23, 2020 at 17:11

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.