omega1 - 1 month ago 15

PHP Question

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.

Answer

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`

.