How do I loop through this array and remove any empty values:
[28] => Array
(
[Ivory] =>
[White] =>
)
[29] => 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).
Another way, using preg_grep:
foreach($array as $key => $subarray) {
$array[$key] = preg_grep('/^$/', $subarray, PREG_GREP_INVERT);
}
Update: Forgot about removing the empty arrays. The technique shown in @Ryan's answer can also be applied here.
You probably need to edit the code below a little.
foreach ($arr as $key => $value) {
if($value == "") {
unset($value[$key]);
}
}
//Check Array Remove Empty Key
$ixx=0; $ix=0;//Set Array First.
while(end(array_keys($a1))>=$ix){ //Check Last Key in Array
if($a1[$ix]!=""){ //Check Empty Key
$ax[$ixx]=$a1[$ix];$ixx++; } //Remove Empty Key
$ix++;
}
//End Check Array Remove Empty Key
print_r($ax);//Print Array After remove Empty Key
For anyone who is looking for cleaning a variable which is a simple array or a multidimensional array (nested array with unknown depth) here is my proposed solution: (it is created as a static function in a class but can work also outside of a class -> just remove self::)
public static function clean($Array, $Strict=true)
{
if( ! is_array($Array))
{
return $Array;
}
$cleaned = array ();
foreach ($Array as $key => $value)
{
if($Strict)
{
if(!empty($value))
{
$tmp = self::clean($value,$Strict);
if(!empty($tmp))
{
$cleaned[$key] = $tmp;
}
}
}//strict
else
{
if(is_array($value))
{
if(!empty($value))
{
$tmp = self::clean($value,$Strict);
if(!empty($tmp))
{
$cleaned[$key] = $tmp;
}
}
}
elseif(strlen($value) > 0)
{
$tmp = self::clean($value,$Strict);
if(strlen($tmp) > 0)
{
$cleaned[$key] = $tmp;
}
}
}//not strict
} //end foreach
return $cleaned;
}
Hope save someone time :) Cheers
I see you already have a working solution, but just for fun, with array_map goodness:
$array = array_filter(array_map('array_filter', $array));