Arithmetic operators
Learn basic arithmetic with +, -, *, /, % and ** operators.
Arithmetic operators
In PHP, the basic four operations on numbers use arithmetic operators: + for addition, - for subtraction, * for multiplication, / for division. These signs keep the meaning they have in everyday math.
For example, to compute a cafe's daily revenue you would write $revenue = $price * $cups;. The operator takes two values, produces a new one and assigns it to the variable.
Modulo and exponentiation
Two more operators will come in handy. % (modulo) gives the remainder of a division: 17 % 5 returns 2 because 17 = 3*5 + 2. It is great for even/odd checks or minute-to-second conversions.
** raises to a power: 2 ** 3 returns 8. The same as multiplying three 2's together. Use it for areas or compound interest.
Exercise Compute the total price
Declare a $total variable and assign the product of $price and $quantity. Then print $total with echo. Use the * multiplication operator.
Show example solution
To find the total, write $total = $price * $quantity and print it with echo.
Example solution:
<?php
$price = 25;
$quantity = 4;
// Total price
$total = $price * $quantity;
echo $total;
Test yourself
-
What is the output of echo 6 * 7;?
echo 6 * 7;- 36
- 42
- 13
- 67
Show answer
42 — Correct. 6 times 7 is 42.
-
Write the remainder operator
$remainder = 17 ____ 5; echo $remainder;Show answer
$remainder = 17 % 5; echo $remainder; -
Match each operator to its meaning
- +
- Addition
- -
- Subtraction
- *
- Multiplication
- /
- Division