PHP Math
PHP ships with a rich set of built-in math functions that cover rounding, roots, powers, trigonometry, and random number generation without any extra library.
Working with the Math Functions
Most everyday calculations in PHP rely on a small group of functions that are always available. They accept integers or floats and return a numeric result, so you can chain them together freely. The examples below focus on the functions you will reach for most often: rounding a price, finding the larger of two values, taking a square root, or raising a number to a power.
Rounding, min, and max
<?php
echo round(3.14159, 2), "\n"; // 3.14
echo ceil(4.1), "\n"; // 5
echo floor(4.9), "\n"; // 4
echo max(2, 9, 5), "\n"; // 9
echo min(2, 9, 5), "\n"; // 2
echo abs(-17), "\n"; // 17
?>The rounding trio is worth distinguishing clearly: round() moves to the nearest value and lets you set the number of decimal places, ceil() always rounds up to the next whole number, and floor() always rounds down. For money you almost always want round() with two decimals, while ceil() and floor() are handy for pagination and bucketing.
Powers, Roots, and the Pi Constant
Exponents and geometry
<?php
echo pow(2, 10), "\n"; // 1024
echo 2 ** 10, "\n"; // 1024 (exponent operator)
echo sqrt(144), "\n"; // 12
$radius = 5;
$area = pi() * pow($radius, 2);
echo round($area, 2), "\n"; // 78.54
?>Generating Random Numbers
PHP offers rand() and mt_rand() for general random values, plus random_int() when the numbers must be unpredictable for security purposes such as tokens or passwords. All three let you pass a minimum and maximum to constrain the range. Prefer random_int() whenever the value guards anything sensitive, because it draws from a cryptographically secure source.
Random values in a range
<?php
echo rand(1, 6), "\n"; // a dice roll, 1 to 6
echo mt_rand(1, 100), "\n"; // faster general-purpose random
echo random_int(1000, 9999), "\n"; // secure 4-digit code
?>Common Math Functions Reference
Exercise: PHP Math
What does round(4.5) return in PHP?