PHP Math
PHP includes a complete set of math functions in its core — no imports needed. This lesson covers the ones you'll reach for most: rounding, absolute values, minimum and maximum, powers and roots, integer division and a few constants.
Basic functions
| Function | Purpose | Example | Result |
|---|---|---|---|
abs($x) |
absolute value | abs(-4.2) |
4.2 |
min(...) / max(...) |
smallest / largest | max(3, 9, 1) |
9 |
pow($b, $e) or $b ** $e |
power | 2 ** 10 |
1024 |
sqrt($x) |
square root | sqrt(81) |
9 |
intdiv($a, $b) |
integer division | intdiv(17, 5) |
3 |
$a % $b |
remainder | 17 % 5 |
2 |
fmod($a, $b) |
float remainder | fmod(7.5, 2) |
1.5 |
array_sum($arr) |
total of an array | array_sum([1,2,3]) |
6 |
<?php
echo abs(-15), "\n";
echo max(4, 18, 7), "\n";
echo min([12, 3, 8]), "\n"; // also accepts an array
echo 2 ** 8, "\n";
echo pow(3, 3), "\n";
echo sqrt(144), "\n";
echo intdiv(17, 5), " remainder ", 17 % 5, "\n";
echo fmod(7.5, 2), "\n";
echo M_PI, "\n";15
18
3
256
27
12
3 remainder 2
1.5
3.1415926535898
Rounding
There are three main rounding functions, and the difference matters when you deal with prices or pages:
| Function | Direction | 4.3 |
4.7 |
-4.3 |
|---|---|---|---|---|
round() |
nearest (halves away from zero) | 4 | 5 | -4 |
floor() |
always down | 4 | 4 | -5 |
ceil() |
always up | 5 | 5 | -4 |
All three return a float. round() also takes a precision argument for decimal places.
<?php
$values = [4.3, 4.5, 4.7, -4.3];
foreach ($values as $v) {
printf("%5.1f round=%-3s floor=%-3s ceil=%s\n", $v, round($v), floor($v), ceil($v));
}
echo round(3.14159, 2), "\n";
echo round(1234.5678, -2), "\n"; // round to hundreds
var_dump(floor(9.99)); 4.3 round=4 floor=4 ceil=5
4.5 round=5 floor=4 ceil=5
4.7 round=5 floor=4 ceil=5
-4.3 round=-4 floor=-5 ceil=-4
3.14
1200
float(9)
Tip: To count how many pages you need for 47 items at 10 per page, use
ceil(47 / 10)— it gives5, because a partial page is still a page.
A practical example: a shopping cart
Let's combine these functions: compute a subtotal, apply a percentage discount, add tax and round to cents.
<?php
$cart = [
["Notebook", 3, 2.49],
["Pen", 10, 0.85],
["Backpack", 1, 34.90],
];
$subtotal = 0;
foreach ($cart as [$name, $qty, $price]) {
$line = $qty * $price;
$subtotal += $line;
printf("%-9s %2d x %6.2f = %7.2f\n", $name, $qty, $price, $line);
}
$discount = round($subtotal * 0.10, 2);
$taxed = round(($subtotal - $discount) * 1.08, 2);
printf("Subtotal: %.2f\n", $subtotal);
printf("Discount: %.2f\n", $discount);
printf("Total incl. 8%% tax: %.2f\n", $taxed);
echo "Boxes needed (5 items each): ", ceil(14 / 5), "\n";Notebook 3 x 2.49 = 7.47
Pen 10 x 0.85 = 8.50
Backpack 1 x 34.90 = 34.90
Subtotal: 50.87
Discount: 5.09
Total incl. 8% tax: 49.44
Boxes needed (5 items each): 3
Note the %% in the printf pattern: it prints a literal percent sign.
Number bases and other helpers
<?php
echo decbin(10), "\n"; // decimal -> binary
echo bindec("1010"), "\n"; // binary -> decimal
echo dechex(255), "\n"; // decimal -> hex
echo hexdec("ff"), "\n";
echo base_convert("777", 8, 10), "\n";
echo hypot(3, 4), "\n"; // length of the hypotenuse
echo round(deg2rad(180), 5), "\n";
echo round(log(M_E), 2), "\n";
echo log10(1000), "\n";1010
10
ff
255
511
5
3.14159
1
3
Random numbers
For random values PHP provides random_int($min, $max), which is cryptographically secure, and the older rand() / mt_rand(). Because their results change on every run, we can't show a fixed output here:
<?php
$dice = random_int(1, 6); // secure, use for tokens and codes
$pick = array_rand(["a", "b", "c"]); // a random key from an arrayNote: For passwords, tokens and anything security-related always use
random_int()orrandom_bytes(), neverrand().
Test yourself
What does floor(-2.5) return?
-2-3-2.52
Which expression gives 3 for 17 split into groups of 5?
17 % 5intdiv(17, 5)ceil(17 / 5)round(17 / 5, 1)
Which function should you use for a secure random token?
rand()mt_rand()random_int()round()