Arithmetic operators
Arithmetic operators in PHP are used to perform mathematical operations on numeric values. Here are the arithmetic operators supported in PHP:
Addition (+)
Adds two numbers together.
$sum = 5 + 3; // $sum is now 8
Subtraction (-)
Subtracts the right operand from the left operand.
$difference = 10 - 4; // $difference is now 6
Multiplication (*)
Multiplies two numbers together.
$product = 2 * 6; // $product is now 12
Division (/)
Divides the left operand by the right operand.
$quotient = 8 / 2; // $quotient is now 4
Modulus (%)
Returns the remainder of the division of the left operand by the right operand.
$remainder = 10 % 3; // $remainder is now 1 (10 divided by 3 equals 3 with a remainder of 1)
Exponentiation
Raises the left operand to the power of the right operand.
$result = 2 ** 3; // $result is now 8 (2 raised to the power of 3)
These arithmetic operators can be used in combination with assignment operators to perform operations and assign the result to a variable in a single step.
$x = 5;
$x += 3; // $x is now 8 (same as $x = $x + 3)
Additionally, parentheses can be used to group operations and control the order of evaluation.
$result = (5 + 3) * 2; // $result is now 16 (the addition is performed first, then the multiplication)