Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Array - Removing empty values

Tags:

arrays

php

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!

like image 756
christian.thomas Avatar asked Apr 21 '11 22:04

christian.thomas


People also ask

How do you remove Blank values from an array?

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.

Is array empty PHP?

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.

What is array filter PHP?

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.


2 Answers

I see you already have a working solution, but just for fun, with array_map goodness:

$array = array_filter(array_map('array_filter', $array));
like image 69
mfonda Avatar answered Oct 03 '22 21:10

mfonda


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).

like image 36
Ryan Avatar answered Oct 03 '22 22:10

Ryan