PHP includes built-in math functions for rounding prices, finding minimum and maximum values, calculating powers, and generating secure random numbers. You do not need to import a separate math library to use them.
Most web applications need predictable rounding for pagination, ratings, and order totals. Pick the function that matches your rounding rule.
| Function | Behavior | Example Input | Output |
|---|---|---|---|
round() |
Rounds to nearest integer or precision | round(4.6) |
5 |
ceil() |
Always rounds up | ceil(4.1) |
5 |
floor() |
Always rounds down | floor(4.9) |
4 |
abs() |
Returns positive distance from zero | abs(-25) |
25 |
<?php
declare(strict_types=1);
$totalItems = 47;
$perPage = 10;
$totalPages = (int) ceil($totalItems / $perPage);
$scores = [78, 92, 64, 88];
echo "Total pages: {$totalPages}" . PHP_EOL;
echo "Lowest score: " . min($scores) . ", Highest: " . max($scores) . PHP_EOL;
echo "Distance: " . abs(-15.5) . PHP_EOL;
Use sqrt() for square roots, the ** exponent operator (or pow()) for powers, and random_int() for unpredictable random numbers.
<?php
declare(strict_types=1);
$sideA = 3;
$sideB = 4;
$hypotenuse = sqrt(($sideA ** 2) + ($sideB ** 2));
$otpCode = random_int(100000, 999999);
echo "Hypotenuse: {$hypotenuse}" . PHP_EOL;
echo "One-time code: {$otpCode}" . PHP_EOL;
Always prefer random_int() over the older rand() function. random_int() uses your operating system's cryptographic random generator, making it safe for verification codes and tokens.
rand() for security codes or passwords: rand() is predictable. Always call random_int() or random_bytes() for security-sensitive values.0 throws a DivisionByZeroError exception in PHP 8. Guard denominators before calculating percentages or averages.round() mode flags: round(2.5) defaults to PHP_ROUND_HALF_UP (3), so verify rounding rules when handling financial tax calculations.pow($a, $b) or $a ** $b?Both calculate powers identically. The ** operator is shorter, faster, and standard in modern PHP 8 code.
Check that the array is not empty, then compute array_sum($numbers) / count($numbers).
fdiv() do in PHP 8?fdiv() performs IEEE 754 floating-point division that returns INF, -INF, or NAN on division by zero instead of throwing an error.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.