php arithmetic operators

Part of the course: php for beginners

PHP Arithmetic Operators

Introduction to PHP Arithmetic Operators

Arithmetic operators in PHP are symbols used to perform basic mathematical operations on numerical values. These operations include addition, subtraction, multiplication, division, and more. PHP uses these operators to calculate and manipulate numbers within variables or expressions.

Arithmetic operators are essential in programming because they allow developers to handle calculations such as totals, averages, percentages, or any numeric processing needed in an application. Whether you are working with integers, floats, or numeric strings, PHP automatically converts values when necessary to ensure the operation is executed correctly.

In simple terms, arithmetic operators help you perform math in your PHP code, making them a fundamental part of building dynamic and logical programs.

 

 

List of Arithmetic Operators in PHP

PHP provides several arithmetic operators that allow you to perform basic mathematical calculations. These operators are commonly used when working with numbers, variables, or expressions in your programs. Below is a list of the primary arithmetic operators in PHP along with what each one does.

2.1 Addition (+)

The addition operator adds two values together.
It is used to calculate sums, totals, or combine numeric variables.

Example:

$a = 10 + 5; // Result: 15

2.2 Subtraction (-)

The subtraction operator subtracts one value from another.

Example:

$a = 10 - 5; // Result: 5

2.3 Multiplication (*)

The multiplication operator multiplies two values.

Example:

$a = 10 * 5; // Result: 50

2.4 Division (/)

The division operator divides one value by another.
It is important to avoid dividing by zero, as it causes an error.

Example:

$a = 10 / 2; // Result: 5

2.5 Modulus (%)

The modulus operator returns the remainder after dividing one number by another.
It is often used to check if a number is even or odd.

Example:

$a = 10 % 3; // Result: 1

2.6 Exponentiation (**)

The exponentiation operator raises a number to the power of another.
This operator was introduced in PHP 5.6.

Example:

$a = 2 ** 3; // Result: 8

Using Arithmetic Operators with Variables

Arithmetic operators in PHP are most commonly used with variables rather than fixed numbers. This allows your programs to perform dynamic calculations based on input, user data, or other changing values. PHP automatically reads the values stored in variables and applies the arithmetic operation.

You can combine two or more variables, or mix variables with numeric values, to perform mathematical operations such as addition, subtraction, multiplication, and more. PHP also supports updating variable values directly using arithmetic operations, which is useful in counters, loops, and real-time calculations.

Example: Basic usage

$x = 10;
$y = 5;
$result = $x + $y; // 15

Example: Updating a variable using arithmetic

$counter = 1;
$counter = $counter + 1; // Now 2

Shorter version using +=

$counter += 1; // Also becomes 2

Using arithmetic operators with variables allows PHP programs to be flexible, calculate results instantly, and build logic based on changing values.

Operator Precedence in PHP

Operator precedence in PHP determines the order in which different operators are evaluated in an expression. When an expression contains multiple operators—such as addition, multiplication, or comparison—PHP follows specific rules to decide which operation to perform first. This ensures that the final result is calculated correctly and consistently.

Operators with higher precedence are executed before those with lower precedence. For example, multiplication and division have higher precedence than addition and subtraction. This means PHP will perform multiplication or division first unless parentheses are used to change the order.

Understanding operator precedence helps you avoid unexpected results in your calculations. Whenever you want to control the order of evaluation, you can use parentheses, which always take the highest priority.

Example:

$result = 10 + 5 * 2;
// Multiplication happens first, so result = 10 + 10 = 20

Using parentheses to change precedence:

$result = (10 + 5) * 2;
// Parentheses first, so result = 15 * 2 = 30

Operator precedence is essential for writing clear, predictable PHP code, especially in complex expressions.

Arithmetic Operations with Different Data Types

In PHP, arithmetic operators can work with different data types, not just integers and floats. PHP is a loosely typed language, which means it automatically converts values to the appropriate numeric type when performing arithmetic operations.

This process is called type juggling.

PHP attempts to interpret the values as numbers whenever possible. However, the behavior may vary depending on the data type involved.

1. Numbers (Integers and Floats)

When both operands are numbers, PHP performs the arithmetic normally.

Example:

$x = 10; // integer
$y = 2.5; // float

$result = $x + $y; // 12.5

2. Numeric Strings

If a string contains a valid number, PHP converts it to a numeric type before performing the operation.

Example:

$a = "20"; // numeric string
$b = 5;

$result = $a + $b; // 25

Only the numeric part of the string is used.
For example:

$x = "30 apples";
$y = 10;

$result = $x + $y; // 40

3. Non-numeric Strings

If the string does not start with a number, PHP converts it to 0, which may lead to unexpected results.

Example:

$a = "hello";
$b = 10;

$result = $a + $b; // 10, because “hello” becomes 0

4. Booleans

Booleans are converted to integers:

  • true1

  • false0

Example:

$result = 10 + true; // 11
$result = 10 + false; // 10

5. Null

null is converted to 0 in arithmetic operations.

Example:

$result = 5 + null; // 5

Common Use Cases and Examples

Arithmetic operators in PHP are used in many everyday programming tasks. These operators help perform calculations, process user input, and manage numeric data inside applications. Below are some common situations where arithmetic operations play an important role.

1. Calculating Totals

Arithmetic operators are often used to calculate totals such as prices, scores, or quantities.

Example:

$price = 50;
$tax = 5;
$total = $price + $tax; // 55

2. Finding Averages

To compute an average, you sum values and divide by the number of items.

Example:

$a = 80;
$b = 90;
$c = 100;
$average = ($a + $b + $c) / 3; // 90

3. Working with Loops (Counters)

Arithmetic is frequently used to update counters inside loops.

Example:

$count = 0;

for ($i = 0; $i < 5; $i++) {
$count += 1; // increases by 1 each time
}

4. Percentage Calculations

Calculating discounts, tax percentages, or progress commonly uses arithmetic operators.

Example:

$original = 200;
$discount = 20; // percent
$finalPrice = $original – ($original * $discount / 100); // 160

5. Checking Even or Odd Numbers (Modulus)

The modulus operator is useful to determine if a number is even or odd.

Example:

$number = 7;

if ($number % 2 == 0) {
echo “Even”;
} else {
echo “Odd”;
}

6. Power Calculations (Exponentiation)

Used in mathematical formulas, algorithms, and scientific calculations.

Example:

$power = 2 ** 4; // 16

Errors and Pitfalls (e.g., Division by Zero)

When working with arithmetic operators in PHP, it’s important to be aware of common errors and mistakes that can occur during calculations. Understanding these pitfalls helps you write safer, more reliable code and avoid unexpected results.

1. Division by Zero

One of the most common arithmetic errors is dividing a number by zero.
In PHP, dividing by zero causes a warning and results in INF (infinity) for floats, or an error for integers.

Example:

$x = 10;
$y = 0;
$result = $x / $y; // Warning: Division by zero

How to avoid it:

if ($y != 0) {
$result = $x / $y;
} else {
echo "Error: Cannot divide by zero.";
}

2. Unexpected Type Conversion

Because PHP performs automatic type juggling, you may get unexpected results when using non-numeric values.

Example:

$result = "hello" + 5;
// "hello" becomes 0, result = 5

To prevent this, always validate or cast values before calculations.

3. Floating-Point Precision Errors

Floating-point numbers cannot always represent decimals accurately, which can lead to small rounding errors.

Example:

$result = 0.1 + 0.2; // May result in 0.30000000000000004

To handle precision issues, use functions like round().

Example:

$result = round(0.1 + 0.2, 2); // 0.30

4. Overflow on Very Large Numbers

Extremely large numbers may exceed PHP’s maximum integer size, causing them to convert to floats or infinity.

Example:

$x = 999999999999999999999;

5. Using Modulus with Negative Numbers

The result of modulus % with negative numbers can be confusing.

Example:

$result = -10 % 3; // Result: -1

6. Incorrect Operator Precedence

If you don’t use parentheses, PHP may evaluate expressions differently than you expect.

Example:

$result = 10 + 5 * 2; // Result: 20, not 30

Use parentheses to clearly define order.

Summary

Arithmetic operators in PHP are essential tools for performing mathematical calculations within your programs. They allow you to add, subtract, multiply, divide, find remainders, and calculate powers using simple symbols. These operators work seamlessly with different data types, and PHP automatically converts values when needed.

Understanding how arithmetic operators behave—especially with operator precedence and different data types—helps you write more accurate and predictable code. It’s also important to be aware of common issues, such as division by zero, floating-point precision errors, and unexpected type conversions.

In short, arithmetic operators form the foundation of many calculations in PHP, making them a crucial part of programming tasks ranging from simple totals to complex formulas.