PHP arithmetic Operators are used to perform mathematical calculations.
Operator | Description |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Modulus |
++ | Increment |
−− | Decrement |
Increment and Decrement operators act on numeric values.
Example:
<?php
$var = 1; // Assign the integer 1 to $var
echo $var++; // Print 1, $var is now equal to 2
echo ++$var; // Print 3, $var is now equal to 3
echo --$var; // Print 2, $var is now equal to 2
echo $var--; // Print 2, $var is now equal to 1
?>
Referencing Variables
By default, assignment operators work by value—that is, they copy the value of an expression on to another. If the right-hand operand happens to be a variable, only its value is copied, so that any subsequent change to the left-hand operator is not reflected in the right-hand one.
Example:
<?php
$a = 5;
$b = $a;
$b = 10;
echo $a; // Print 5
?>
Naturally, you expect this to be the case, but there are circumstances in which you may want an assignment to take place by reference so that the left-hand operand becomes "connected" with the right-hand one:
Example:
<?php
$a = 5;
$b = &$a; // Reference
$b = 10;
echo $a; // Print 10
?>