steve Kim steve Kim - 5 months ago 14
PHP Question

php array_filter for "False" value

I am using

array_filter
in php:

$new_array = array_filter($updated, "check_if_value_is_null_or_false");

function check_if_value_is_null_or_false($val) {
return !is_null($val);
};


I understand that I can use
is_null
to filter out anything that has
null
value.

I also want to add a condition for string
"False"
as the value.

How would I modify the above?

Answer

Well you could make your own callback

function is_not_null_or_false($value) {
  return !(is_null($value) || $value === false);
}

array_filter($updated, 'is_not_null_or_false');

Or you could skip the separate function and do

array_filter($updated, function($x) { return !(is_null($x) || $x === false); });

EDIT

it appears you're looking for the string "False" not the boolean value

array_filter($updated, function($x) { return !(is_null($x) || $x === "False"); });

EDIT 2

For readability's sake, we changed

!is_null($x) && $x !== "False"

To

!(is_null($x) || $x === "False")

According to De Morgan's Laws these are equivalent but the second probably reads better especially given the function's name.