I am attempting to use both AND and OR statements in my IF/ELSE statement, but I cannot get the desired effect.
What I would like to achieve is that if either 'a' or 'b' has a value of '1' but both 'c' and 'd' must be 1 then I get 'Yes'.
All my attempts have given me either 'Yes' or have not worked (blank screen).
<?php
$a = "0";
$b = "1";
$c = "1";
$d = "1";
if (($a == "1") || ($b == "1") && ($c == "1") && ($d == "1")) {
echo "Yes";
}
else {
echo "No";
}
?>
Thank you.
You need and extra parenthesis, to make sure the evaluation order will be done correctly, like in math:
if ( ( ($a == "1") || ($b == "1") ) && ($c == "1") && ($d == "1")) {
^ ^
That way, let's say for example:
$a = 1;
$b = 2;
$c = 1;
$d = 2;
The first parenthesis will be evaluated as true || false. The final result will be true.
So now you have true && ($c == "1") && ($d == "1")
$c = 1, so again, the next evaluation will be true && true && ($d == 1)
$d = 2, so the next round will be true && true && false, final result, in this example, will be false.
You need to add parenthesis.
Why?
Because inner parenthesis are evaluated first before outer parenthesis. Take this example:
((1 == 1 && (2 == 2)) || 3 == 3)
What will be evaluated first? The 2 == 2 then the 1 == 1 and then the 3 == 3. In your if condition, because you are mixing AND's and OR's, you will not get the desired affect.
( (($a == "1") || ($b == "1")) && ($c == "1") && ($d == "1") )
Should work for you. In fact you can do this so that it looks even better:
(($a == 1 || $b == 1) && $c == 1 && $d == 1)
Because it is not necessary to put 1 in quotes ie: "1". PHP's truthiness will evaluate 1 == "1" to be true. However if you wanted to check for an actual string that contains 1, then you would use the === operator.
$a = 1;
$b = "1"
$a == "1"; // true
$b == 1; // true
$a === "1"; // false
$b === "1"; // true
However for more information go here: http://php.net/manual/en/language.operators.precedence.php
The equality operators will be evaluated first, then &&, then ||. Parentheses will be evaluated before anything else, so adding them can change the order.
Check the answer In Java, what are the boolean "order of operations"?
It will always echo a Yes because PHP interpreter places The AND operation before the OR operation.
So your if statement interpretes like this:
If
a = 1 or b = 1 and c = 1 and d = 1
then
echo 'Yes'
else
echo 'No'
That's why you always get a yes..
Related
In php the following code gives a warning of undefined variable $x:
if($x = 1 && $x == 1)
I thought it was equivalent to if( ($x = 1) && ($x == 1) ), but that's not the case. I've been told, it's because && has higher precedence than =, which causes the expression to get converted to:
if($x = (1 && ($x == 1)))
So far so good, but now consider:
$x=1; if($x == 1 && $x = 2)
This doesn't throw error. Why doesn't it get converted to:
$x=1; if( (($x == 1) && $x) = 2 )
I've been told thats due to = being right assosiative, but https://www.php.net/manual/en/language.operators.precedence.php says When operators have equal precedence their associativity decides how the operators are grouped.. Here we have =, && and == all being of different precedence.
P.S; My actual code is if($result != false && $res = $stmt->get_result()), which has been copied from some other reputable source, so seems like not using unneeded parenthesis is common in php.
I've played with several conditions and below is what I've got.
First, let's consider that we init $x before if statements to avoid undefined variable notice.
Second, let's confirm the precedence for operators:
== is applied 1st
&& is applied 2nd
= is applied 3rd
This returns true:
$x = 1;
if ($x = 1 && $x == 1) {
echo 'true';
} else {
echo 'false';
}
It goes like ($x = (1 && ($x == 1))) -> ($x = (1 && true)) -> ($x = true) -> true.
If we compare $x to another value than the assigned one we will get false:
$x = 1;
if ($x = 2 && $x == 2) {
echo 'true';
} else {
echo 'false';
}
It goes like ($x = (2 && ($x == 2))) -> ($x = (2 && false)) -> ($x = false) -> false.
The last one returns true:
$x = 1;
if ($x == 1 && $x = 2) {
echo 'true';
} else {
echo 'false';
}
It goes like ((($x == 1) && $x) = 2) -> ((true && $x) = 2) -> (true = 2) -> true.
The last comparison can't be interpreted by PHP so it's an approximate view.
It looks like the last action (true = 2) totally depends on the left operand. If we put $x = 2; we will get (false = 2) -> false.
I'm not sure about the last one and here is the only place were some mistakes can happen.
Otherwise, it looks like precedence works as expected.
Anyway, I always put parenthesis for an assignment action inside if operator (especially inside ternary if) to be sure that I will get what I expect.
I don't think this affects performance or readability too much, but it may prevent some logical errors.
UPDATE:
Concering your code if($result != false && $res = $stmt->get_result()) it's not correct to compare it to if($x == 1 && $x = 2) because in your code are two different variables.
In this case logical operator will not call the second part at all if the fisrt one is false, see the 1st example here
UPDATE-2:
After the discussion under this answer we can see that the last conditions ($x == 1 && $x = 2) work like like (($x == 1) && ($x = 2)) -> ((1 == 1) && 2) -> true and $x becomes 2 after it.
This seems pretty simple, but I can't figure that out.
I am checking a few variables before showing some stuff on the screen, and I have a variable which can be null at some point.
On my if statement I have:
if ($a != 'abc' && ($a == $b || $b == $c) && min($variable) > 3) { ... }
How can I set it true if min($variable) is null, if all the other statements are true?
As I understood from your question,
the min($variable) maybe null and you want to check it whether it's value less than 3 or null value ?
if ($a != 'abc' && ($a == $b || $b == $c)
&& (min($variable) > 3 || min($variable) == null)) { ... }
could be using a ternary operator inside ( )
if ($1 != 'abc' && ($1 == $2 || $2 == $3) &&
( $variable == null ? true : min($variable) > 3) ) { ... }
Any ideas how to shorten if statment in an elegant way.
My if statement:
if(getfoo1() == getfoo2() && getfoo2() == 1)
{
}
EDIT:
I'm looking for something like:
if(getfoo1() == getfoo2() ==1)
{
}
But I suppose we can't do this.
$a = getfoo1();
$b = getfoo2(); // less operations, while it not produces duplicate calls
if($a == $b && $b == 1){
// do something
}
$variable = ((getfoo1() == getfoo2() && getfoo2() == 1) ? $value1 : $value2);
More elegant, combined:
$a = getfoo1();
$b = getfoo2();
$variable = (($a == $b && $b == 1) ? $value1 : $value2);
Since we don't know the possible return values from the functions, if you assume they are integers then you can say:
$a = getfoo1();
$b = getfoo2();
if (($a * $b) === 1) { // strict equality for the win
echo 'hi';
}
The result would only be true iff both $a AND $b are 1.
Another way:
$both = array(getfoo1(), getfoo2());
// use array_diff_assoc so it checks multiple occurrences of the same value
$diffCount = count(array_diff_assoc($both, array(1, 1)));
if ($diffCount === 0) {
echo 'hi';
}
Since anyway getfoo2() == 1 must be true, a better approach is to first check whether getfoo2() is equal to 1. If it false no matter about 2nd condition. But If you first check getfoo1() == getfoo2() and and then check getfoo2() == 1 you have to check 2 conditions all the times.
Therefore go for
$a = getfoo1();
$b = getfoo2();
if($b == 1 && $a == $b)
{
// logiv
}
else
{
}
Try this.
$a = getfoo1();
$b = getfoo2();
if( intval($a && $b) === 1) {
echo 'hi';
}
Am I correct in thinking that the below statement will validate if $a is either '1' or '0', and $b is either 'x' or 'y'
if ($a == '1' && $b == 'x' || $b == 'y')
or do I have to be more specific, i.e.
if ($a == '1' && $b == 'x' || $a == '1' && $b == 'y')
You need to use parenthesis to specify precedence:
if ($a == '1' && ($b == 'x' || $b == 'y'))
if (($a == '1' && $b == 'x') || ($a == '1' && $b == 'y'))
You need this:
if (($a == '1') && ($b == 'x' || $b == 'y'))
The first would be sufficent for that, but you have to put a parenthesis around $b:
if ($a == '1' && ($b == 'x' || $b == 'y'))
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
How can I set one variable to true based on other conditions. Here, instead of doing
if ($vara && $varb && $varc)
I'm something like below. Problem is, I'm just not getting something right. Can you please help me?
<?php
$onward = false;
$vara = 11;
$varb = 21;
$varc = 3;
if ($vara == 1)
{$onward = true;}else{$onward = false;}
if ($varb == 2)
{$onward = true;}else{$onward = false;}
if ($varc == 3)
{$onward = true;}else{$onward = false;}
if ($onward)
{
echo "Ok";
}else {echo "Not ok";}
?>
Each of your conditions ignores the result of the previous condition. You need to include the previous state of $onward in each subsequent test:
if ($vara == 1)
{$onward = true;}else{$onward = false;}
if ($varb == 2 && $onward)
{$onward = true;}else{$onward = false;}
if ($varc == 3 && $onward)
{$onward = true;}else{$onward = false;}
This way, varb and varc are only tested if $onward is still true after the previous test.
This is a particularly ugly way of writing code. If you have three large conditions and you don't simply want to join them on one line as in your $vara && $varb && $varc, you should be writing it this way:
$onward = ($vara == 1)
$onward = $onward && ($varb == 2);
$onward = $onward && ($varb == 3);
Any time you're simply returning/setting something to true/false in the branches if your if statement, you should just be returning/setting the condition itself.
That is, this:
if (condition) {
return true;
} else {
return false;
}
should always be written:
return condition;
The problem is, you are overwriting the value of $onward in every if-statement. Just use
$onward = $vara == 1 && $varb == 2 && $varc == 3;
I think you are looking for:
$onward = $vara == 1 || $varb == 2 || $varc ==3;
or
$onward = $vara == 1 && $varb == 2 && $varc == 3;
depending on your goal.
With this:
if ($varc == 3)
{$onward = true;}else{$onward = false;}
$onward will always be false if $varc is not 3.
I'm sure you mean
if (($vara == 1) && ($varb == 2) && ($varc == 3))
{$onward = true;}else{$onward = false;}
or even
$onward = (($vara == 1) && ($varb == 2) && ($varc == 3));
A better way of doing this:
if ($vara == 1) {$onward = true;} else {$onward = false;}
is this:
$onward = ($vara == 1);
You're overwriting the same variable each time, so the first two conditions are actually pointless.
I don't know why you'd want to do this over the first, more succinct approach, which will have the same logical effect:
if ($varc ==== 1 || $varc === 2 || $varc === 3)
$onward = true;
else
$onward = false;
Or even just:
$onward = $varc === 1 || $varc === 2 || $varc === 3;
Beware also of ever doing == 1. In comparisons, data are coerced to their truthy/falsy equivalents, so any truthy value will resolve to true in the comparison == 1. To test that something is literally 1, use ===. (This is a good rule generally unless you know you explicitly want to test for value and not type.)