0
0
PhpHow-ToBeginner · 3 min read

How to Use Arithmetic Operators in PHP: Simple Guide

In PHP, you use +, -, *, /, and % to perform addition, subtraction, multiplication, division, and modulus operations respectively. These operators work between numbers to calculate and return a result.
📐

Syntax

Arithmetic operators in PHP are used between two numbers (operands) to perform calculations. The common operators are:

  • + for addition
  • - for subtraction
  • * for multiplication
  • / for division
  • % for modulus (remainder)

Example syntax: $result = $a + $b; adds two variables.

php
<?php
$a = 10;
$b = 3;
$sum = $a + $b;  // adds 10 and 3
$difference = $a - $b;  // subtracts 3 from 10
$product = $a * $b;  // multiplies 10 by 3
$quotient = $a / $b;  // divides 10 by 3
$remainder = $a % $b;  // remainder of 10 divided by 3
?>
💻

Example

This example shows how to use arithmetic operators to calculate and print results of basic math operations.

php
<?php
$a = 15;
$b = 4;

echo "Addition: " . ($a + $b) . "\n";
echo "Subtraction: " . ($a - $b) . "\n";
echo "Multiplication: " . ($a * $b) . "\n";
echo "Division: " . ($a / $b) . "\n";
echo "Modulus: " . ($a % $b) . "\n";
?>
Output
Addition: 19 Subtraction: 11 Multiplication: 60 Division: 3.75 Modulus: 3
⚠️

Common Pitfalls

Common mistakes include dividing by zero, which causes errors, and misunderstanding the modulus operator which returns the remainder, not the quotient.

Also, using arithmetic operators on non-numeric strings can lead to unexpected results or warnings.

php
<?php
// Wrong: division by zero causes error
// $result = 10 / 0; // Warning: Division by zero

// Right: check divisor before dividing
$divisor = 0;
if ($divisor != 0) {
    $result = 10 / $divisor;
} else {
    $result = 'Cannot divide by zero';
}
echo $result;
?>
Output
Cannot divide by zero
📊

Quick Reference

OperatorDescriptionExampleResult
+Addition5 + 38
-Subtraction5 - 32
*Multiplication5 * 315
/Division5 / 22.5
%Modulus (remainder)5 % 21

Key Takeaways

Use +, -, *, /, and % to perform basic math operations in PHP.
Always check for division by zero to avoid errors.
Modulus (%) returns the remainder after division, not the quotient.
Arithmetic operators work best with numeric values to avoid unexpected results.
Use parentheses to control operation order when combining multiple operators.