Can you conditionally negate a function in PHP?
For example
$x = true;
return (($x ? "!" : "" ). is_null(NULL));
This obviously doesn't work, is there a way to do it?
The goal is to refactor this
$var == true
? array_filter($labels, function($v){return str_contains($v, 'return');})
: array_filter($labels, function($v){return !str_contains($v, 'return');});
Thanks
A common way of describing boolean combinations is as a truth table listing the possible inputs and outputs. In this case:
$x | is_null($var) | Desired result |
---|---|---|
false | false | false |
false | true | true |
true | false | true |
true | true | false |
So, the result you want is "either $x
is true, or is_null($var)
is true, but not both".
Looking in the PHP manual under "logical operators", we see that that's the definition of the xor
operator, so you could write this:
return $x xor is_null($var);
An intermediate variable and simple if
statement as shown in Justinas's answer is probably a lot more readable, though. Readability is extremely important in programming, because code is read far more times than it's written.
You can, but with different approach: first execute function and then check if it needs to be inverted
$result = is_null($var);
if ($x) {
// invert result from e.g. true to false
$result = !$result;
}
is_null
returns a boolean. $x
is a boolean. Compare both booleans:
return is_null($var) != $x;