2

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?

6
  • Do you mean the string "False" or the false value as a Boolean? Commented Jun 8, 2016 at 22:49
  • Opps. Should have clarified it. I meant for string. Commented Jun 8, 2016 at 22:51
  • Where are you stuck? Show your research / attempts. Commented Jun 8, 2016 at 22:55
  • I'm slightly confused by your function name compared to what it's doing. You are stating check_if_value_is_null_or_false as you would return true if the value is null or "False". Although inside you are returning "not null", would you want to return the true value or false for the second one? Commented Jun 8, 2016 at 22:55
  • I don't think my explanation was clear. But I got it working now. Thanks guys. Commented Jun 8, 2016 at 22:58

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You could also do !(is_null($value) || $value === false), it might make more sense given the function name.
@SpencerWieczorek thanks, you're probably right. I updated the answer and provided reasoning.
-2

Please check this example:

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

more information: http://php.net/manual/en/types.comparisons.php empty() return TRUE when variable is null and false.

1 Comment

0, "0", "", false, and [] would also be filtered out. This does not meet the OP's specs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.