1

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?

2
  • Actually, array_filter works very well in this case. Commented Dec 12, 2013 at 18:12
  • Tried, didnt work. So many answers! Im gonna test them all, and post results. Commented Dec 12, 2013 at 18:48

3 Answers 3

3

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.

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

1 Comment

Yes, this works. The end result is "Array ()", so I only had to add "if (empty($arr)) unset $arr".
3

For PHP >= 5.3

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

1 Comment

This works too, at least for 1 level nesting - I'm using PHP 5.5, so it works like a charm. Thank you.
0

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 Comment

This will not work as expected if the array index exists but whose value is the empty string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.