4

I have an array that looks like this:

$arr = array(

  'abc' => array(
             'subkey1' => '',
             'subkey2' => false,             
             'subkey3' => 0,  
             ...                          
           ),

  'def' => array(
             'subkey1' => '',
             'subkey2' => 555,             
             'subkey3' => 0,  
             ...                          
           ),

  ...

);

I want to unset all parent elements in which ALL subkeys have empty values, like 0, '', false, null. In my example abc needs to be unset.

Currently I'm manually checking within a foreach loop if each subkey is empty, but the if condition is huge because I have 8 subkeys :)

Is there a nicer alternative for this?

3
  • Dont you mean abc should be unset in this case? Commented Jun 23, 2012 at 19:51
  • What you are doing seems the right way, you could use recursion, but the condition will be as huge as well. Commented Jun 23, 2012 at 19:52
  • it has to be done using loops. cant see any other way Commented Jun 23, 2012 at 19:53

2 Answers 2

8
$array = array_filter($array, 'array_filter');

View the output on codepad

Array
(
    [def] => Array
        (
            [subkey1] => 
            [subkey2] => 555
            [subkey3] => 0
        )

)

The outer array_filter() will loop over the array and call the inner array_filter() on each sub array, which will remove all subkeys which are empty. If each subkey is empty, the outer array_filter() should then remove the whole sub array.

If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed.

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

7 Comments

I was just about to post this. Also, whenever possible, I find it better to stick with built-in methods over custom ones.
+1. only thing is this still removes the empty child entries of valid entries. You could use the keys from this result and combine with orig array if thats a prob.
Good point... but what do you mean by You could use ... with orig array?
$final = array_intersect_key($origArray, array_filter($origArray, 'array_filter'))
It seems it isn't necessary, look at codepads output: codepad.org/bFe22vZj The empty subkeys of def are still there for some reason.
|
0

How about this:

foreach ($arr as $index=>$element)
{
  if (in_array(0, $element))
  {
    unset($arr[$index]);
  }
}

1 Comment

How about an explanation about this? ;)

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.