How do I loop through this array and remove any empty values:
[28] => Array
(
[Ivory] =>
[White] =>
)
[29] => Array
(
[Ivory] =>
[White] =>
)
[30] => Array
(
[Ivory] =>
[White] => 36
)
[31] => Array
(
[White] => 24
)
So say it'd remove 28, 29 and just Ivory from 30...
Thanks!
In order to remove empty elements from an array, filter() method is used. This method will return a new array with the elements that pass the condition of the callback function.
Using sizeof() function: This method check the size of array. If the size of array is zero then array is empty otherwise array is not empty.
The array_filter() function filters the values of an array using a callback function. This function passes each value of the input array to the callback function. If the callback function returns true, the current value from input is returned into the result array.
I see you already have a working solution, but just for fun, with array_map goodness:
$array = array_filter(array_map('array_filter', $array));
I believe this will do what you're looking for:
foreach( $array as $key => $value ) {
if( is_array( $value ) ) {
foreach( $value as $key2 => $value2 ) {
if( empty( $value2 ) )
unset( $array[ $key ][ $key2 ] );
}
}
if( empty( $array[ $key ] ) )
unset( $array[ $key ] );
}
It will loop through your outer array, descend into any arrays it contains and remove keys whose values are empty. Then, once it's done that, it will remove any keys from the outer array whose subvalues were all empty, too.
Note that it wouldn't work for a generic array, just the one you've provided (two-dimensional).
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