Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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) 
like image 710
Kanishka Panamaldeniya Avatar asked Jan 03 '13 06:01

Kanishka Panamaldeniya


1 Answers

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'); 
like image 178
mgherkins Avatar answered Sep 22 '22 03:09

mgherkins