Reputation: 100
i have 1 array with more arrays inside, and im trying to remove one of those arrays if they have a null key or its empty. Im doing this on PHP.
What i have:
Array
(
[0] => Array
(
[emp] =>
[fun] => 1
[data] =>
[data_d] =>
[desc] =>
)
[1] => Array
(
[emp] => teste
[func] => 1
[data] => 2021-08-30
[data_d] => 2021-09-01
[desc] => testetetetete
)
[2] => Array
(
[emp] => ersfewqef
[func] => 2
[data] => 2021-08-26
[data_d] => 2021-08-28
[desc] => dvgdgvqevgqe
)
)
This means that the [0]
will be removed because has one or more empty values. Is this possible? I have no clue on how to do this.
Upvotes: 0
Views: 97
Reputation: 969
You can use array_filter
and array_intersect
to check for a number of needles in your haystack.
$newArray = array_filter($array, function($v) {
if( empty(array_intersect($v, [null, ""])) &&
empty(array_intersect(array_keys($v), [null, ""])) ) {
return $v;
}
});
Upvotes: 1
Reputation: 41810
I think the other answers are on the right track with array_filter
, but as far as how to identify which inner arrays have falsey values, you can just use array_filter
again.
$result = array_filter($outer, fn($inner) => array_filter($inner) == $inner);
If an array is equal to its filtered value, then it does not contain any empty values, so using that comparison in your filter callback will remove all of the inner arrays with any empty values.
Just remember if you use this that any of the values listed here evaluate to false, so if you don't consider those "empty", you'll need to add a callback to the inner array_filter
to make it more selective.
Upvotes: 1
Reputation: 19
You can use array_filter
to filter elements of an array using a callback function.
If no callback is supplied, all empty entries of array will be removed. See empty()
for how PHP defines empty in this case.
Upvotes: 1
Reputation: 45
You can use array_filter
for this (maybe not the cleanest)
$result = array_filter($data, function($v, $k) {
#return true of false :: if true, then item is added in $result
return empty($v['emp']) || empty($v['data']) ... ;
}, ARRAY_FILTER_USE_BOTH );
Upvotes: 1