I'm writing a functional that calls two nullable boolean APIs. If either API returns true, my function should return true. If both return false, my function should return false. Otherwise, my function should return null. In other words:
true, true -> true
true, false -> true
true, null -> true
false, false -> false
false, null -> null
null, null -> null
Is there a simple/elegant way to write this? Obviously an if-else chain like this would work, but I think it's fairly messy, especially since you have to account for that null is a falsy value.
if ($cond1 || $cond2) {
return true;
} else ($cond1 === false && $cond2 === false) {
return false;
} else {
return null;
}
Stick to what you suggested. One point of improvement is that you don't need if - else branching since you're returning. You just need two ifs:
function evaluate(?bool $cond1, ?bool $cond2): ?bool
{
if ($cond1 || $cond2) {
return true;
}
if ($cond1 === false && $cond2 === false) {
return false;
}
return null;
}
What about
return ($cond1 ? $cond1 : $cond2);
what about :
if($cond1 === true || $cond2 === true){
return true;
}else{ //check first and sec cond for falsing
if($cond1 === false && $cond2 === false){
return false;
}else{ //else null it
return null;
}
}
You can remove else if block like so:
if ($cond1 || $cond2) {
return true;
}
return !isset($cond1, $cond2) ? null : false;
You can simplify it down to:
return ($cond1 || $cond2) ? true : (!isset($cond1, $cond2) ? null : false)
But this gets hard to read and make sense of off.
Given your stipulations (and assuming each argument is one of: null, true or false) you could shave a smidgeon:
function foo($a, $b) {
if($a || $b) return true;
if([$a, $b] === [false, false]) return false;
}
Below seems to be working, I have tried to logic using Javascript as illustrated below
function testMyConditions($c1, $c2) {
return ($c1 === true || $2 === true) ? true: ($c1 === null || $c2 === null ? null: false)
}
function testMyConditions($cond1, $cond2) {
return ($cond1 === true || $cond2 === true) ? true: ($cond1 === null || $cond2 === null ? null: false)
}
function runTests($cond1, $cond2, $expected) {
console.log($cond1, $cond2, $expected, $expected === testMyConditions($cond1, $cond2) ? '=> OK': '=> NOT OK')
}
runTests(true, true, true)
runTests(true, false, true)
runTests(true, null, true)
runTests(false, false, false)
runTests(false, null, null)
runTests(null, null, null)
Related
How to convert string to conditional boolean
example string with boolean condition.
$condition1 = 'false || ( true && false)'; // should return false
$condition2 = 'false || true'; // should return true
$condition3 = 'true && false'; // should return false
$condition4 = 'true && (true || false); // should return true
I tried these codes but not working..
$result = (boolean) $condition1;
$result = filter_var($condition1, FILTER_VALIDATE_BOOLEAN);
$result = settype($condition1, 'boolean');
is there a way to convert it?
You can use php eval() function
eval("\$status=true || false; return \$status;")
In your case
eval('\$condition1 = false || ( true && false);');
eval('\$condition2 = false || true;');
// And so on ...
What is the difference, specifically in PHP? Logically they're the same (or so seem), but is there any advantage with one over the other? Including micro-benchmarking if any difference.
Example code:
$a = fc();
// Example 1
if (!$a) echo "Ex. 1";
// Example 2
if (false === $a) echo "Ex. 2";
// Example 3
if (true !== $a) echo "Ex. 3";
function fc()
{
return false;
}
!
Just invert your result value (boolean or not) from true to false or false to true
Example:
if (!file_exists('/path/file.jpg')) {
// if file NOT exists
}
=== false (or true)
The value compared MUST BE a boolean false or true.
Example:
$name = 'Patrick Maciel';
if ($name === true) {
// not is, because "Patrick Maciel" is a String
}
BUT if you do that
if ($name == true) {
// it is! Because $name is not null
// and the value is not 'false': $name = false;
}
In this case, this operator is just for check that:
$connection = $this->database_connection_up();
if ($connection === true) {
echo 'connected to database';
} else {
echo 'error in connection';
}
$valid_credit_card = $this->validate_credit_card($information);
if ($valid_credit_card === false) {
echo 'Your credit card information is invalid'
}
!== true (or false)
It's the same thing. Only the opposite of ===, ie: the value cannot be a boolean true or false.
Sorry for my english.
The difference boils down to type juggling. The ! operator converts a value to its boolean value, then inverts that value. === false simply checks if the value is, in fact, false. If it's not false, the comparison will be false.
If the value being compared is guaranteed to be a boolean, these operations will behave identically. If the value being compared could be a non-boolean, the operations are very much different. Compare:
php > $a="0";
php > var_dump(!$a);
bool(true)
php > var_dump($a === false);
bool(false)
php > $a = false;
php > var_dump(!$a);
bool(true)
php > var_dump($a === false);
bool(true)
I'm sorry for the vaguely described title. This is what I want:
if($a[$f] === false || $a[$g] === false || $a[$h] === false || $a[$i] === false || $a[$j] === false)
{
// do something
}
I want to do something with the condition that actually triggered the statement (if a[$f] = true and a[$g] = false, I want to do something with $g).
I know that in this case, the first statement that went true (i.e. $a[$g] == false) triggers. But is there any way to do something with $g? I've never seen this in my programming life before and can't seem to find anything about it.
Thanks in advance.
--- Edit ---
I forgot to mention: I'm using a function on all the array data. So, shortened, I get this:
if(valid($a[$f]) === false || valid($a[$g]) === false)
{
// do something
}
--- Edit 2 ---
This piece of OOP-based PHP, where I'm in a class, is my code.
if($this->validatedText($product[$iName]) == false ||
$this->validatedUrl($product[$iUrl]) == false ||
$this->validatedNumber($product[$iTax]) == false ||
$this->validatedValuta($product[$iPrice]) == false ||
$this->validatedText($product[$iArticleNumber]) == false ||
$this->validatedText($product[$iDescription]) == false ||
$this->validatedText($product[$iMetaDescription]) == false ||
$this->validatedText($product[$iTitle]) == false)
{
// do something with the first iVariable
}
Simplest solution will be
if(false!==($sIndex = array_search(false, $a, 1)))
{
//your $sIndex is first index with false value
}
if you want all keys, you may use array_filter(), like this:
$rgFalse = array_keys(array_filter($a, function($x)
{
//here valid is your function
return false===valid($x);
}));
What does an exclamaton mark in front of a variable mean? And how is it being used in this piece of code?
EDIT: From the answers so far I suspect that I also should mention that this code is in a function where one of the parameters is $mytype ....would this be a way of checking if $mytype was passed? - Thanks to all of the responders so far.
$myclass = null;
if ($mytype == null && ($PAGE->pagetype <> 'site-index' && $PAGE->pagetype <>'admin-index')) {
return $myclass;
}
elseif ($mytype == null && ($PAGE->pagetype == 'site-index' || $PAGE->pagetype =='admin-index')) {
$myclass = ' active_tree_node';
return $myclass;
}
elseif (!$mytype == null && ($PAGE->pagetype == 'site-index' || $PAGE->pagetype =='admin-index')) {
return $myclass;
}`
The exclamation mark in PHP means not:
if($var)
means if $var is not null or zero or false while
if(!$var)
means if $var IS null or zero or false.
Think of it as a query along the lines of:
select someColumn where id = 3
and
select someColumn where id != 3
! negates the value of whatever it's put in front of. So the code you've posted checks to see if the negated value of $mytype is == to null.
return true; //true
return !true; //false
return false; //false
return !false; //true
return (4 > 10); //false
return !(4 < 10); //true
return true == false; //false
return !true == false; //true
return true XOR true; //false
return !true XOR true; //true
return !true XOR true; //false
! before variable negates it's value
this statement is actually same as !$mytype since FALSE == NULL
!$mytype == null
statement will return TRUE if $mytype contains one of these:
TRUE
number other than zero
non-empty string
elseif (!$mytype == null && ($PAGE->pagetype == 'site-index' || $PAGE->pagetype =='admin-index')) {
return $myclass;
}
The above !$mytype == null is so wrong. !$mytype means that if the variable evaluates to false or is null, then the condition will execute.
However the extra == null is unnecessary and is basically saying if (false == null) or if (null == null)
!$variable used with If condition to check variable is Null or Not
For example
if(!$var)
means if $var IS null.
Could I do this in PHP?
if ($Var = $this->test1() == true) {
var_dump($Var);
}
public function test1() {
return true;
}
It echoes true, but I'm not sure if this is the correct way to check such return values.
Yes you can, but write:
if (($var = $this->test1()) === true) {
var_dump($var);
}
To be safe and to alert the reader there is something going on.
I wouldn't advise you to do this though, but in some cases this is acceptable; such as a complex if-else tree where lazy execution is desirable.
if (($result = slow_process()) !== false) {
return $result;
} else if (($result = slow_process1()) !== false) {
return $result;
} else if (($result = slow_process2()) !== false) {
return $result;
} else if (($result = slow_process3()) !== false) {
return $result;
}
This is overly simplified, but these situations do occur.
You can but there is 2 things you should be aware of :
When you do something like :
if ($Var = $this->test1() == true) {
The operators are confusing :
do you want to do $this->test1() == true and store result $var
do you want to do $var = $this->test1() and compare it with true
In your case, $this->test1() returns true so it does not matter. But if we change your code a bit :
if ($Var = $this->test1() == 5) {
var_dump($Var);
}
public function test1() {
return 3;
}
Someone who read your code will not understand if you want to store $this->test1() in $Var (so, make 3 in var) or if you want to put result of comparison $this->test1 == 5 in $Var (false).
What remains in $Var at the end may be a very good question at the PHP 5.3 Certification but not in a useful case.
To avoid mistakes, uses parenthesis :
if (($var = $this->test1()) == true) {
You should take care of types :
I give you an example of what could return something castable to true :
function test1() { return true; }
function test2() { return 3; }
function test3() { return 3.42; }
function test4() { return "x"; }
function test5() { return array('x'); } // array() == true returns false
function test6() { return new stdClass(); }
echo test1() == true;
echo test2() == true;
echo test3() == true;
echo test4() == true;
echo test5() == true;
echo test6() == true;
// outputs 111111 (1 = true)
To avoid mistakes, you should use === operator. Your final piece of code becomes :
if (($var = $this->test1()) === true) {
The == true part is unnecessary. What you have is valid syntax, but some find it confusing. You can always do:
$Var = $this->test1();
if ($Var) { ...
Just decide on the standard with your development team.
You can also do:
if ($Var = $this->test1()) {
var_dump($Var);
}
public function test1() {
return true;
}