tags:

views:

81

answers:

1
foreach($array as $key => $value)
        if (strlen($value) == 0)
    unset($array[$key]);

theres so many built-in array functions so is there one that does this?

+13  A: 

I suppose you could use array_filter, to do that kind of thing (quoting) :

Iterates over each value in the input array passing them to the callback function.
If the callback function returns true, the current value from input is returned into the result array.
Array keys are preserved.

And :

If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed.


For instance, using something like this portion of code :

$array = array(
    'test' => 'glop',
    'a' => 123,
    'b' => '',
    'c' => 'blah',
    'd' => '',
);

$array = array_filter($array);
var_dump($array);

You'd get the following output :

array
  'test' => string 'glop' (length=4)
  'a' => int 123
  'c' => string 'blah' (length=4)

I didn't used a callback function, here -- which means that all "empty" values have been removed ;; the tricky part being that if I had en entry with 0 as its value, it would have been removed too...

Depending on your situation, that would be acceptable or not... So maybe you'd prefer to use a specific callback function to do exactly what you want, and have a better control over what gets filtered out ?


And here's an example with a callback function :

$array = array(
    'test' => 'glop',
    'a' => 0,
    'b' => '',
    'c' => 'blah',
    'd' => '',
);

function my_function($a) {
    if ($a === '') {
        return false;
    }
    return true;
}

$array = array_filter($array, 'my_function');
var_dump($array);

(Note the 'a' => 0 line in the array)

And we now get :

array
  'test' => string 'glop' (length=4)
  'a' => int 0
  'c' => string 'blah' (length=4)

i.e. using a callback function allowed us to specify more clearly what should be filtered out (here, lines containing exactly an empty string, without type conversion).

Pascal MARTIN