PHP comes with a set of built-in math functions. You do not need a library for everyday calculations.
| Function | What it does | Example |
|---|---|---|
abs($n) | Absolute value (removes the minus) | abs(-5) gives 5 |
sqrt($n) | Square root | sqrt(16) gives 4 |
pow($a, $b) | Power, same as ** | pow(2, 3) gives 8 |
intdiv($a, $b) | Whole-number division | intdiv(7, 2) gives 3 |
fmod($a, $b) | Remainder for floats | fmod(7.5, 2) gives 1.5 |
pi() or M_PI | The number pi | 3.14159... |
floor($n) | Round down | floor(4.9) gives 4 |
ceil($n) | Round up | ceil(4.1) gives 5 |
<?php
echo abs(-12) . "\n";
echo sqrt(81) . "\n";
echo pow(2, 10) . "\n";
echo intdiv(17, 5) . "\n";
echo fmod(10.5, 3) . "\n";
echo M_PI;
12
9
1024
3
1.5
3.1415926535898
An area calculator
<?php
function circleArea(float $radius): float
{
return M_PI * $radius ** 2;
}
echo round(circleArea(5), 2);
78.54
Powers and roots
<?php
echo 2 ** 8 . "\n"; // 256
echo 27 ** (1 / 3) . "\n"; // cube root: 3
echo sqrt(2);
256
3
1.4142135623731
Logarithms and trigonometry
PHP also has log(), log10(), exp(), sin(), cos(), tan() and their relatives. Angles are in radians, not degrees.
<?php
echo round(sin(deg2rad(30)), 2) . "\n";
echo log10(1000) . "\n";
echo round(exp(1), 4);
0.5
3
2.7183
Check before you calculate
Some maths operations have no valid answer. sqrt(-1) returns NAN (not a number).
<?php
$result = sqrt(-1);
var_dump(is_nan($result));
bool(true)
Constants help
M_PI, M_E and PHP_INT_MAX are ready to use. Do not type 3.14 by hand when M_PI is more accurate.