PHP

➕ Arithmetic Operators in PHP

Arithmetic operators in PHP are used with numeric values to perform common mathematical operations such as addition, subtraction, multiplication, division, and modulo. Depending on the operands, the calculated result will be an integer or a floating-point (float) number.

  • Basic Concept: Arithmetic operators can act as binary operators (operating on two numbers, e.g., $a + $b) or unary operators (operating on a single number, e.g., -$a).

🛠️ Operators and Usage Examples

1️⃣ Identity (+5) and Negation (-5)
Unary operators indicate or convert the sign of a single numeric value:

PHP
// Identity (+) - Maintains the positive sign
echo +5;   // Outputs: 5
echo +8.8; // Outputs: 8.8

// Negation (-) - Converts the value to negative
echo -5;   // Outputs: -5
echo -8.8; // Outputs: -8.8

2️⃣ Addition (+) and Subtraction (-)
Performs basic arithmetic sum or difference between two values:

PHP
// Addition (+)
echo 5 + 8;    // Outputs: 13
echo 5 + 8.8;  // Outputs: 13.8
echo 5 + -3;   // Outputs: 2

// Subtraction (-)
echo 8 - 5;    // Outputs: 3
echo 8.8 - 5;  // Outputs: 3.8
echo 5 - -3;   // Outputs: 8

3️⃣ Multiplication (*), Division (/), and Modulo (%)
Handles scaling, splitting, or calculating the integer division remainder:

PHP
// Multiplication (*)
echo 5 * 8;    // Outputs: 40
echo 5 * 8.8;  // Outputs: 44
echo 5 * -3;   // Outputs: -15

// Division (/)
echo 8 / 2;    // Outputs: 4
echo 4.5 / 1.5; // Outputs: 3
echo 8 / -2;   // Outputs: -4

// Modulo (%) - Returns the remainder of division
echo 5 % 2;    // Outputs: 1
echo 10 % 2;   // Outputs: 0

📊 Quick Reference Table

Operator Name Example Result
+$a Identity +$a Conversion of $a to int or float according to sign.
-$a Negation -$a Opposite sign of $a.
+ Addition $a + $b Sum of $a and $b.
- Subtraction $a - $b Difference of $a and $b.
* Multiplication $a * $b Product of $a and $b.
/ Division $a / $b Quotient of $a and $b.
% Modulo $a % $b Remainder of $a divided by $b.
  • 📝 Short Summary

  • Use standard math operators (+, -, *, /) for everyday calculations in scripts.
  • The modulo operator (%) is especially helpful for checking odd/even numbers or cycle patterns.
  • Division involving float values automatically converts the result to a float type.