I\'ve been looking a lot of answers, but none of them are working for me.
This is the data assigned to my $quantities
array:
Array(
Because the subarrays in your array only have one element each, you can simplify the approach using either of the two following methods. The logical advantage is in avoiding the functional iterator (array_filter
) on the second level elements. This is why current()
is more suitable for this question/page.
Code: (Demo)
$quantities=[
10=>['25.00'=>1],
9=>['30.00'=>3],
8=>['30.00'=>4],
12=>['35.00'=>null],
1=>['30.00'=>''],
2=>['30.00'=>null]
];
var_export(array_filter($quantities,function($a){return strlen(current($a));}));
OR
foreach($quantities as $key=>$sub){ // could be done "by reference" but that impacts code stability
if(!strlen(current($sub))){ // if subarray value has no length
unset($quantities[$key]);
}
}
var_export($quantities);
Both output the same result (which purposely removes empty values and preserves 0
values)
array (
10 =>
array (
'25.00' => 1,
),
9 =>
array (
'30.00' => 3,
),
8 =>
array (
'30.00' => 4,
),
)
In the above methods, strlen()
is used to check the 2nd level elements because the OP only listed integers as the "non-empty" values. Future SO readers may have different requirements based on the elements possibly holding false
, null
, '0'
, 0
, etc. Suitable replacement functions for strlen()
may be: any of the "is_" functions, empty(), any of the "ctype" functions, and many more.
If the OP's 2nd level array held more than one element AND the OP wanted to remove all zero-ish, false-y, empty, null elements (meaning zeros are not wanted or guaranteed not to occur), then Alastair F's answer would be the best choice.
If the OP's input array had an unknown number of levels AND zero-ish/false-y/empty/null elements should be removed, then Reza Mamun's answer is a logical, recursive approach.
My point being (and my motivation behind spending so much time and care to answer this question) that array_filter()
is greedy and if you aren't aware of this default behavior, your project may silently output incorrect information. I hope this explanation saves programmers some time and strife.