Arithmetic operators help you do math with numbers in your program. They let you add, subtract, multiply, and divide values easily.
0
0
Arithmetic operators in PHP
Introduction
Calculating the total price of items in a shopping cart.
Finding the difference between two dates or times.
Increasing a score in a game after a player earns points.
Splitting a bill evenly among friends.
Converting units, like inches to centimeters.
Syntax
PHP
$result = $a + $b; $result = $a - $b; $result = $a * $b; $result = $a / $b; $result = $a % $b;
Use + for addition, - for subtraction, * for multiplication, / for division, and % for remainder (modulus).
Make sure variables hold numbers before using arithmetic operators.
Examples
Adds 5 and 3, then prints 8.
PHP
$sum = 5 + 3; echo $sum;
Subtracts 4 from 10, then prints 6.
PHP
$difference = 10 - 4; echo $difference;
Multiplies 7 by 6, then prints 42.
PHP
$product = 7 * 6; echo $product;
Finds remainder when 10 is divided by 3, then prints 1.
PHP
$remainder = 10 % 3; echo $remainder;
Sample Program
This program shows all basic arithmetic operations between 15 and 4, printing each result on a new line.
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"; ?>
OutputSuccess
Important Notes
Division by zero will cause an error, so avoid dividing by zero.
Modulus operator (%) gives the remainder after division, useful for checking even/odd numbers.
Summary
Arithmetic operators let you do basic math in PHP.
Use +, -, *, /, and % for addition, subtraction, multiplication, division, and remainder.
Always check your numbers to avoid errors like dividing by zero.