Numbers and Math

Prices, totals, and the arithmetic behind every checkout page

7 min read

Websites do math constantly. Cart totals, discount percentages, how many days until an event, page 3 of 12. In this lesson you will learn how PHP handles numbers, and you will be pleased to hear it works almost exactly like the math you already know.

Two kinds of numbers

PHP has whole numbers, called integers, like 3, 0, and -42, and decimal numbers, called floats, like 9.99 and 3.14. Notice that numbers are written without quotes. 7 is a number you can do math with; "7" is a string, a piece of text that happens to look like a number.

The basic operators

<?php
$a = 10;
$b = 3;
echo $a + $b;
echo $a - $b;
echo $a * $b;
echo $a / $b;
echo $a % $b;
?>
  • + adds: 13
  • - subtracts: 7
  • * multiplies: 30
  • / divides: 3.3333...
  • % gives the remainder after division: 1, because 3 goes into 10 three times with 1 left over

That last one, called modulo, sounds obscure but is genuinely handy. Checking whether a number is even is just asking whether $number % 2 equals 0. Striping every other row of a table works the same way.

Order of operations

PHP follows the math rules you learned in school: multiplication and division happen before addition and subtraction.

<?php
echo 2 + 3 * 4;
echo (2 + 3) * 4;
?>

The first line prints 14, because 3 * 4 happens first. The second prints 20, because parentheses always win. When in doubt, add parentheses; they cost nothing and make your intent obvious.

A tiny checkout

Here is math doing real website work:

<?php
$price = 24.50;
$quantity = 3;
$shipping = 4.99;
$total = $price * $quantity + $shipping;
echo "Your total is $" . $total;
?>

This prints Your total is $78.49. A real store computes every order total with arithmetic exactly like this.

Updating a number in place

You will often want to change a number based on its current value. PHP has friendly shortcuts:

<?php
$score = 10;
$score = $score + 5;
$score += 5;
$score++;
echo $score;
?>

The first two additions do the same thing: $score += 5 is just a shorter way to write add 5 to score. The ++ adds exactly 1, so the final result here is 21. You will see ++ everywhere once loops enter the picture.

Careful: $total = $price * $quantity uses the values at that moment. If $price changes later, $total does not magically update. Variables store results, not ongoing relationships.

Quick check

Q1 What does 10 % 3 evaluate to in PHP?

Q2 What does echo 2 + 3 * 4; print?

Want to save your progress? It's free.

Create a free account