views:

298

answers:

2

So I am porting a VBA application to PHP and ran into this wonderful little nugget of code:

expr1 = expr2 Mod expr3 = 0

I thought it was behaving like a ternary operator but when I broke it down to simple if then statements the outcome was not as expected. So I ask the brilliant stack**overflow** community to help me out and put it in easy to understand terms. I know by looking at the other answers I will not be let down. [/end brown_nose>]

+4  A: 

It is the modulus operator:

a MOD b = remainder of a/b

in PHP it is the % sign:

a%b

see php documentation here

So the line

expr1 = expr2 Mod expr3 = 0

means: expr1 is true, if expr2 can be divided by expr3 without any remainders: eg:

20 MOD 5 = 0 ==> TRUE
22 MOD 5 = 2 ==> FALSE
Peter Parker
but what is the = 0 on the end used for?
txmail
Wow tough to assign the answer to, I choose Peter since he wrote back with a better explanation (even though while it was coming in I was asking Jacob almost the same thing. You both rock. Thanks!
txmail
+6  A: 

It's assigning expr1 to a boolean value that indicates whether expr2 can be divided evenly (with no remainder) by expr3. Remember that = means == in VB :D.

Here's what it would look like with the implied parentheses:

expr1 = ((expr2 Mod expr3) = 0)
Jacob
Why would the = operator right-associate? I would sort of expect that `a = b = c` associates as `(a = b) = c`.
Greg Hewgill
So is it correct to think like this:Using your example if:expr2 = 2expr3 = 4expr1 would be true (1)?
txmail
Maybe my wording was backwards, but no. The remainder of 2 / 4 is 2, so that would evaluate to False. But if expr2 is 4 and expr3 is 2, then it would evaluate to True.
Jacob
Actually, I think I was backwards. Thanks!
txmail