Remove NULL, FALSE, and '' - but not 0 - from a PHP array

Kanishka Panamaldeniya picture Kanishka Panamaldeniya · Jan 3, 2013 · Viewed 26.1k times · Source

I want to remove NULL, FALSE and '' values .

I used array_filter but it removes the 0' s also.

Is there any function to do what I want?

array(NULL,FALSE,'',0,1) -> array(0,1)

Answer

mgherkins picture mgherkins · Jan 3, 2013

array_filter should work fine if you use the identical comparison operator.

here's an example

$values = [NULL, FALSE, '', 0, 1];

function myFilter($var){
  return ($var !== NULL && $var !== FALSE && $var !== '');
}

$res = array_filter($values, 'myFilter');

Or if you don't want to define a filtering function, you can also use an anonymous function (closure):

$res = array_filter($values, function($value) {
    return ($value !== null && $value !== false && $value !== ''); 
});

If you just need the numeric values you can use is_numeric as your callback: example

$res = array_filter($values, 'is_numeric');