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?
$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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With