Gixxy22
Gixxy22

Reputation: 507

Multiple && and ||?

I am trying to make a statement with multiple ANDS and ORS, is this possible?

This is what i currently have:

elseif ($a == 'promo' && strstr(ucwords($promo_name),'30% Off') && $b == 'yes')
{echo 'this is a 30% off promotion'; }

I am looking to echo the same message if the $promo_name has either '30% Off' OR 'Save 30%'.

Would I be correct with this?

elseif ($a == 'promo' && strstr(ucwords($promo_name),'30% Off') || 
        strstr(ucwords($promo_name),'Save 30%') && $b == 'yes')
{echo 'this is a 30% off promotion'; }

Im getting a little confused with what will take precedence etc. I need both $a == 'promo' and $b == 'yes' to be true at all times, with any 1 of the 2 strstr being true.

Any help much appreciated.

thanks

m,ike

Upvotes: 0

Views: 1271

Answers (3)

svvac
svvac

Reputation: 6134

When I first studied boolean algebra in electronics, we were told that and was like a × and or like a +. This is true for operator precedence (a and b or c translates to a × b + c and hence (a × b) + c), and also helps for truth tables or complicated boolean expressions, expression development, etc.

a   b   a×b   a+b
0   0    0     0
0   1    0     1
1   0    0     1
1   1    1    2=1

This is a good mnemonic, but don't ever say that to a mathematician ;-)

So, just to be clear, and has higher precedence than or so yo need parenthesis to do what you'd like : bool1 and (bool2 or bool3)

Upvotes: 0

Prinsig
Prinsig

Reputation: 245

Try something like

if ((($a == "a") || ($b == "b")) && ($foo == "bar")) {

Upvotes: 1

colburton
colburton

Reputation: 4715

The precedence of && is higher than ||. So you need to use some parentheses to make your statement work, as you expect:

elseif ($a == 'promo' && (strstr(ucwords($promo_name),'30% Off') || strstr(ucwords($promo_name),'Save 30%')) && $b == 'yes')

Upvotes: 5

Related Questions