0

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.

omega1
  • 1,031
  • 4
  • 21
  • 41

4 Answers4

3

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.

Felippe Duarte
  • 14,901
  • 2
  • 25
  • 29
1

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

Paul Carlton
  • 2,785
  • 2
  • 24
  • 42
0

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"?

Community
  • 1
  • 1
Nandan Bhat
  • 1,573
  • 2
  • 9
  • 21
0

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..

pamekar
  • 729
  • 7
  • 10