Reputation: 11545
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?
Upvotes: 4
Views: 3817
Reputation: 68588
How about this:
foreach ($arr as $index=>$element)
{
if (in_array(0, $element))
{
unset($arr[$index]);
}
}
Upvotes: 0
Reputation: 13257
$array = array_filter($array, 'array_filter');
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.
Upvotes: 8