Combining Arithmetic & Assignment Operators

Posted by tutor | Posted in PHP Tutorial | Posted on 12-12-2009-05-2008

0

We often need to increment a variable by a fixed amount. For eg a variable which is being used to count something, may be a counter for a loop or some other purpose, we need to constantly increment it by 1.

    $count = $count + 1;

However, there is another way for doing this.

    $counter += 1;

This combined assignment/arithmetic operator would accomplish the same task as the above code.

Although this combined operator shortens the code but sometimes for those who are not accustomed to such programming constructs, this may create confusion and may make the code unreadable.0

    Operator Description Example Expanded Form
    += Plus Equals $x += 2; $x = $x + 2;
    -= Minus Equals $x -= 4; $x = $x – 4;
    *= Multiply Equals $x *= 3; $x = $x * 3;
    /= Divide Equals $x /= 2; $x = $x / 2;
    %= Modulo Equals $x %= 5; $x = $x % 5;
    .= Concatenate Equals $my_str.=”PHP”; $my_str = $my_str .”PHP”;

Write a comment

Twitter Users
Enter your personal information in the form or sign in with your Twitter account by clicking the button below.