Remove empty arrays with empty values

126 views Asked by At

Right to the point. I have a form that submits a multidimensional array of values. Usually it gets something like this.

[0] => Array
    (
        [socialClass] => Myclass
        [socialLink] => http://...
        [socialName] => Name
    )

[1] => Array
    (
        [socialClass] => 
        [socialLink] => MyClass
        [socialName] => Name
    )

[2] => Array
    (
        [socialClass] => 
        [socialLink] => 
        [socialName] => 
    )

The idea es to remove incomplete arrays from the tree, like [1] and [2], so i would return like this after the filter.

[0] => Array
    (
        [socialClass] => Class
        [socialLink] => http://...
        [socialName] => Name
    )

array_filter doesn't work in this case, and other "recursive" custom made functions either. How can I do it?

3

There are 3 answers

1
AudioBubble On BEST ANSWER

The following array_filter call with a custom filter function should do the trick for you:

$arr = array_filter($arr, function($sub_arr) {
    foreach ($sub_arr as $item)
        if ($item === "")
            return false;
    return true;
});

You'll note that the item will be removed if any of its sub-array values is the empty string.

1
Mathieu Dumoulin On

Array filter would be great in this exact case:

$result = array_filter($input, function($a){
    return isset($a['socialClass']) 
           && isset($a['socialLink']) 
           && isset($a['socialName'])
           && !empty($a['socialClass']) 
           && !empty($a['socialLink']) 
           && !empty($a['socialName']);
});

This should work!

1
evalarezo On

For PHP >= 5.3

$myarray = array_filter($myarray, function ($node) {
    return count(array_filter($node)) == count($node);
});