Monday, 30 September 2013

PHP mathmatical assignment operators

This is another post on some basic PHP stuff which isn't so obvious to new PHP developers, even some people who've been coding for a while didn't know this just because it hasn't been brought to their attention.

What are they?

They are just short cut ways of taking a variable and performing either an addition, subtraction, multiplication or division on them with less code. I've put examples below including what they do and what the 'long hand' way of doing it would've been.

Mathematical operationLong handShort hand
Addition$var1 = $var1 + 2$var1 += 2
Subtraction$var1 = $var1 - 2$var1 -= 2
Multiplication$var1 = $var1 * 2$var1 *= 2
Division$var1 = $var1 / 2$var1 /= 2


One more

There is one more which is the modulo assignment operator. I've put this separately as it's not as obvious as the the ones above (unless you know your maths of course). This divides the first number (called first operand) by the second number (called second operand) and the result would be the remainder of the division (called modulus).

Mathematical operationLong handShort hand
ModuloN/A$var1 %= 2


Further reading

1 comment: