PHP Arithmetic Assignment Operators

PHP provides arithmetic assignment operators which combine arithmetic operations and assignment in a single operation. These operators are useful when you want to update a variable’s value by performing an arithmetic operation on it.

Here are the arithmetic assignment operators in PHP:

  1. Addition assignment operator: += 

The addition assignment operator adds the value on the right-hand side to the value on the left-hand side and assigns the result to the left-hand side variable.

<?php

$a = 5;
$b = 3;
$a += $b;  // $a now contains 8

?>
  1. Subtraction assignment operator: -=

The subtraction assignment operator subtracts the value on the right-hand side from the value on the left-hand side and assigns the result to the left-hand side variable.

Example:

<?php

$a = 10;
$b = 3;
$a -= $b;  // $a now contains 7

?>
  1. Multiplication assignment operator: *=

The multiplication assignment operator multiplies the value on the left-hand side by the value on the right-hand side and assigns the result to the left-hand side variable.

Example:

<?php

$a = 2;
$b = 5;
$a *= $b;  // $a now contains 10
?>
  1. Modulus assignment operator: %=

The modulus assignment operator calculates the remainder of the division of the left-hand side by the right-hand side and assigns the result to the left-hand side variable.

Example:

<?php

$a = 10;
$b = 3;
$a %= $b;  // $a now contains 1

?>

These arithmetic assignment operators can be combined with any arithmetic operation and are very useful for shortening code and improving readability..

Example for PHP Arithmetic Assignment Operators

<?php
$num = 2;
$num += 2; // New value is 4
echo "New value is $num <br />";
$num -= 1; // New value is 3
echo "New value is $num <br />";
$num *= 4; // New value is 12
echo "New value is $num <br /> ";
$num /= 2; // New value is 6
echo "New value is $num <br />";
$num %= 4; // New value is 2
echo "New value is $num<br />";
?>