davidasor
davidasor

Reputation: 329

PHP : cannot remove empty array

im trying to remove only the empty array

Array
(
    [test1] =>  test1
    [test2] =>  test2
    [test3] =>  
)

i have tried the following :

$array = array_filter(array_map('array_filter', $array));

and

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 ] );
}

also i have tried to avoid adding any empty array :

foreach($attributes_array as $key => $single_attribute){
 if(!empty($attributes_array)){
  $attributes[$attributes_array[$key]['attribute_name']] = $attributes_array[$key] ['attribute_value'];     
 }
} 

any of the following code wont work in my case, any other possible soultion?

Upvotes: 1

Views: 31

Answers (1)

cOle2
cOle2

Reputation: 4784

If your definition of empty is the same as empty() you can use array_filter without a callback:

$array = array_filter($array);

Otherwise you can define a callback function to use with array_filter for your empty rules:

$array = array_filter($array, function($val) {
    return $val !== '';
});

Demo: https://3v4l.org/lGhUC

Upvotes: 1

Related Questions