How to declare several conditions within an if

Asked

Viewed 3,133 times

6

I have two ifs which take into account 3 conditions, one of which has multiple possibilities.

I’m doing it like this, but it’s not working:

if (($var1 == $var2) && ($var3 == 1 || 3 || 5 || 7 || 8 || 12) && ($var4 > 16)) {
    $var5--;
}

if (($var1 == $var2) && ($var3 == 4 || 6 || 9 || 11) && ($var4 > 15)) {
    $var5--;
}

In my tests the script is always taking 2 of $var5, when it was to take out only 1, because $var3 will never match in both cases. So I guess he’s not considering this condition. I have already researched here, and all the examples I have found show at most two conditions.

What is the correct way to declare several conditions within one if, and some of these conditions may have multiple possibilities and may use other operators within the ($var3 in the example above). Thanks.

  • 2

    On your first if do so: if (($var1 == $var2) && ($var3 == 1 || $var3 == 3 || $var3 == 5 || $var3 == 7 || $var3 == 8 || $var3 == 12) && 
 ($var4 > 16)) {, apply the same logic in the second if.

  • Ah, that was it, thanks! Always need to repeat the variable right...

1 answer

9


Like the qmechanik said, would need to be

($var3 == 1 || $var3 == 3 || $var3 == 5 || $var3 == 7 || $var3 == 8 || $var3 == 12)

That’s because the way you did it, 1 || 3 || 5 || 7 || 8 || 12 is understood as a single expression ($var3 == (1 || 3 || 5 || 7 || 8 || 12)), which results in 1, that is true.

Another way to do it is to use in_array, gets a little cleaner:

$opcoesVar3 = array(1, 3, 5, 7, 8, 12);
if (($var1 == $var2) && in_array($var3, $opcoesVar3) && ($var4 > 16)) {
    $var5--;
}
  • Hadn’t even imagined doing with array. + 1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.