PHPMath Functions

Math Functions

PHP ships a large set of numeric functions in the global namespace — there is no Math class or Math object to import, no use statement to write. You just call abs(), round(), pow(), and friends directly, anywhere, on any expression that produces a number. That flat, always-available design is convenient, but it also means it's worth knowing the full toolbox rather than reinventing pieces of it with loops and conditionals.

Absolute value, rounding, and boundaries

abs() strips the sign from a number. round(), ceil(), and floor() all deal with fractional parts but round in different directions: round() goes to the nearest whole number (with a configurable number of decimal places), ceil() always rounds up, and floor() always rounds down — regardless of how close the fractional part is to either boundary.

abs, round, ceil, floor

PHP
<?php

echo abs(-12.5) . PHP_EOL;    // 12.5
echo round(3.456, 2) . PHP_EOL; // 3.46
echo round(3.4) . PHP_EOL;    // 3
echo round(3.5) . PHP_EOL;    // 4  (rounds half away from zero by default)
echo ceil(3.01) . PHP_EOL;    // 4
echo floor(3.99) . PHP_EOL;   // 3
echo ceil(-3.01) . PHP_EOL;   // -3  (ceil rounds toward positive infinity)
echo floor(-3.01) . PHP_EOL;  // -4  (floor rounds toward negative infinity)
12.5
3.46
3
4
4
3
-3
-4
ceil() and floor() always return float
Even when the result is mathematically a whole number, `ceil()` and `floor()` return a `float`, not an `int`. Cast explicitly with `(int)` if you need an integer type downstream — for example before passing the value to a function with a strict `int` type hint.
Powers and roots

pow($base, $exponent) raises a number to a power, and the ** operator does exactly the same thing as an infix operator — pick whichever reads better in context. sqrt() computes a square root and returns NAN (not a number) for negative input rather than throwing, so check the sign first if negative input is possible.

pow(), **, and sqrt()

PHP
<?php

echo pow(2, 10) . PHP_EOL;   // 1024
echo 2 ** 10 . PHP_EOL;      // 1024 — identical result, operator form
echo pow(9, 0.5) . PHP_EOL;  // 3    — fractional exponent = a root
echo sqrt(81) . PHP_EOL;     // 9

$result = sqrt(-4);
var_dump(is_nan($result));   // bool(true) — no exception thrown
1024
1024
3
9
bool(true)
min() and max()

min() and max() accept either a list of individual arguments or a single array, and return whichever value is smallest or largest. They work on mixed types too, following PHP's comparison rules, but it's best practice to only compare values of the same type to avoid surprising results.

min() and max() with args or an array

PHP
<?php

echo max(4, 19, 7) . PHP_EOL;        // 19
echo min([4, 19, 7, -3]) . PHP_EOL;  // -3

$prices = [12.99, 8.50, 21.00, 5.25];
echo 'Cheapest: ' . min($prices) . PHP_EOL;
echo 'Priciest: ' . max($prices) . PHP_EOL;
19
-3
Cheapest: 5.25
Priciest: 21
Summing and multiplying whole arrays

Rather than looping manually to total up a list, array_sum() and array_product() reduce an entire array to a single number in one call. Both quietly skip over non-numeric string keys and coerce numeric strings, so keep the array's contents genuinely numeric to avoid confusing results.

array_sum() and array_product()

PHP
<?php

$cart = [12.99, 8.50, 21.00];

echo 'Subtotal: ' . array_sum($cart) . PHP_EOL;

$dice = [4, 6, 2];
echo 'Product: ' . array_product($dice) . PHP_EOL;
Subtotal: 42.49
Product: 48
Beyond native precision: bcmath and gmp

Every function above ultimately operates on PHP's native int and float types, which means they inherit the same limits: a finite integer range and imprecise binary floats. When you need exact arithmetic beyond those limits — huge integers (cryptography, big counters) or exact decimal math (currency totals with many operations) — reach for the bcmath extension (bcadd, bcmul, bcdiv, all operating on numeric strings at arbitrary precision) or gmp for very large integer arithmetic. Both trade a small performance cost for correctness that native floats can't provide.

bcmath sidesteps float rounding

PHP
<?php

// Native float arithmetic accumulates rounding error over many operations
$total = 0.0;
for ($i = 0; $i < 10; $i++) {
    $total += 0.1;
}
var_dump($total === 1.0); // bool(false) — tiny binary rounding error

// bcmath works on strings at fixed, exact decimal precision
$bcTotal = '0';
for ($i = 0; $i < 10; $i++) {
    $bcTotal = bcadd($bcTotal, '0.1', 1);
}
var_dump($bcTotal === '1.0'); // bool(true) — exact
bool(false)
bool(true)

Function

Purpose

abs($n)

Absolute value

round($n, $precision)

Round to nearest, configurable decimal places

ceil($n) / floor($n)

Always round up / down, returns float

pow($b, $e) / $b ** $e

Exponentiation

sqrt($n)

Square root; NAN for negative input

min(...) / max(...)

Smallest/largest of args or an array

array_sum($a) / array_product($a)

Total or product of an array

  • All of these are plain global functions — no Math class, no import, no namespace to bring in.

  • ceil() and floor() always return float, even for whole-number results.

  • sqrt() of a negative number returns NAN instead of throwing — check with is_nan().

  • For arithmetic that must be exact beyond native int/float limits, use bcmath or gmp instead.

Tip
If a calculation involves money, don't reach for `round()` at the end and hope it's close enough. Either work in integer cents throughout, or use `bcmath` with a fixed scale from the very first operation — retrofitting precision after rounding errors have already accumulated doesn't recover the lost accuracy.