Math

suggest change

PHP has two numeric types, int (64-bit signed on all modern builds) and float (IEEE 754 double), and a large set of built-in math functions that are always available, no extension required. This article covers arithmetic operators and their edge cases, rounding, the standard math functions, number bases, special float values, comparing floats safely, and when to switch to arbitrary precision with BCMath or GMP.

All examples were run with PHP 8.5.

Arithmetic operators

<?php
var_dump(7 + 2);    // addition
var_dump(7 - 2);    // subtraction
var_dump(7 * 2);    // multiplication
var_dump(7 / 2);    // division: float when not exact
var_dump(8 / 2);    // division: int when exact
var_dump(7 % 2);    // modulo (remainder)
var_dump(7 ** 2);   // exponentiation
var_dump(2 ** -1);  // negative exponent gives a float
var_dump(-7);       // negation

Output:

int(9)
int(5)
int(14)
float(3.5)
int(4)
int(1)
int(49)
float(0.5)
int(-7)

The / operator returns an int only if both operands are integers and the division is exact. Otherwise you get a float. If you mix an int and a float in any operation, the result is a float.

The ** operator is right-associative and binds tighter than unary minus, so -2 ** 2 is -(2 ** 2):

<?php
var_dump(2 ** 3 ** 2);  // 2 ** (3 ** 2) = 2 ** 9
var_dump(-2 ** 2);
var_dump((-2) ** 2);

Output:

int(512)
int(-4)
int(4)

Every operator has a compound assignment form: +=, -=, *=, /=, %=, **=. See Operators and Altering operator precedence with parentheses for the full precedence table.

Integer division and remainders

intdiv() performs integer division and truncates toward zero. The % operator converts both operands to int and the result takes the sign of the dividend (left operand). For floats use fmod():

<?php
var_dump(intdiv(7, 2));
var_dump(intdiv(-7, 2));   // truncates toward zero, not -4
var_dump(7 % 3);
var_dump(-7 % 3);          // sign follows the dividend
var_dump(7 % -3);
var_dump(fmod(7.5, 2));    // float remainder
var_dump(fmod(-7.5, 2));

Output:

int(3)
int(-3)
int(1)
int(-1)
int(1)
float(1.5)
float(-1.5)

% is an integer operator: 7.9 % 3 converts 7.9 to 7 and emits a deprecation notice ("Implicit conversion from float 7.9 to int loses precision"). Use fmod() when you work with floats, and convert explicitly with (int) when truncation is what you want.

Because -7 % 3 is -1, the naive $n % 2 == 1 test fails for negative odd numbers. If you need a remainder that is always non-negative (for example to wrap an index around an array), use this helper:

<?php
function mod(int $a, int $n): int
{
    return (($a % $n) + $n) % $n;
}

$days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
echo $days[mod(0 - 1, 7)], "\n";  // one day before Monday
echo $days[mod(-15, 7)], "\n";
var_dump(-7 % 2 !== 0);           // correct way to test "is odd"

Output:

Sun
Sun
bool(true)

Division by zero

Dividing an integer or float by zero with /, %, intdiv() throws DivisionByZeroError. intdiv(PHP_INT_MIN, -1) throws ArithmeticError because the result doesn't fit in an int:

<?php
foreach ([
    fn() => 1 / 0,
    fn() => 1 % 0,
    fn() => intdiv(1, 0),
    fn() => intdiv(PHP_INT_MIN, -1),
] as $f) {
    try {
        $f();
    } catch (ArithmeticError $e) {
        echo get_class($e), ": ", $e->getMessage(), "\n";
    }
}

Output:

DivisionByZeroError: Division by zero
DivisionByZeroError: Modulo by zero
DivisionByZeroError: Division by zero
ArithmeticError: Division of PHP_INT_MIN by -1 is not an integer

DivisionByZeroError extends ArithmeticError, so catching ArithmeticError handles both.

If you want IEEE 754 semantics instead (infinity and NaN), use fdiv():

<?php
var_dump(fdiv(1, 0));
var_dump(fdiv(-1, 0));
var_dump(fdiv(0, 0));
var_dump(fmod(1, 0));

Output:

float(INF)
float(-INF)
float(NAN)
float(NAN)

Integer limits and overflow

<?php
var_dump(PHP_INT_SIZE);   // bytes
var_dump(PHP_INT_MAX);
var_dump(PHP_INT_MIN);

$x = PHP_INT_MAX;
var_dump($x + 1);         // silently becomes a float
var_dump(PHP_INT_MAX * 2);

Output:

int(8)
int(9223372036854775807)
int(-9223372036854775808)
float(9.223372036854776E+18)
float(1.8446744073709552E+19)

Integer overflow never throws: the result silently turns into a float, which can represent large magnitudes but has only 53 bits of precision. Integers above 2 ** 53 can't all be represented exactly as floats:

<?php
$big = 2 ** 53;
var_dump($big + 1);                       // int arithmetic: exact
var_dump((float) $big + 1);               // float arithmetic: the +1 is lost
var_dump((float) $big + 1 == (float) $big);
var_dump(PHP_FLOAT_DIG);                  // decimal digits that survive a round trip

Output:

int(9007199254740993)
float(9007199254740992)
bool(true)
int(15)

If you need exact integers beyond PHP_INT_MAX, use GMP or BCMath (see below). For more on integer basics see Integers.

Rounding

round(), floor() and ceil() always return a float, even for integer input. Cast with (int) if you need an integer:

<?php
var_dump(round(3.4));
var_dump(round(3.5));
var_dump(round(-3.5));          // half away from zero by default
var_dump(round(3.14159, 2));    // round to 2 decimal places
var_dump(round(1234567, -3));   // negative precision rounds to tens, hundreds...
var_dump(floor(-3.5));          // toward negative infinity
var_dump(ceil(-3.5));           // toward positive infinity
var_dump((int) 3.99);           // cast truncates toward zero
var_dump((int) -3.99);
var_dump((int) round(2.7));

Output:

float(3)
float(4)
float(-4)
float(3.14)
float(1235000)
float(-4)
float(-3)
int(3)
int(-3)
int(3)

The default rounding mode rounds halves away from zero. PHP 8.4 added the RoundingMode enum, which offers more modes, including banker's rounding (half to even), common in finance and statistics because it doesn't bias sums upward:

<?php
$values = [0.5, 1.5, 2.5, -2.5, 2.4];
$modes = [
    RoundingMode::HalfAwayFromZero,
    RoundingMode::HalfTowardsZero,
    RoundingMode::HalfEven,
    RoundingMode::HalfOdd,
    RoundingMode::TowardsZero,
    RoundingMode::AwayFromZero,
    RoundingMode::NegativeInfinity,
    RoundingMode::PositiveInfinity,
];
foreach ($modes as $mode) {
    $out = array_map(fn($v) => round($v, 0, $mode), $values);
    printf("%-17s %s\n", $mode->name, implode(' ', $out));
}

Output:

HalfAwayFromZero  1 2 3 -3 2
HalfTowardsZero   0 1 2 -2 2
HalfEven          0 2 2 -2 2
HalfOdd           1 1 3 -3 2
TowardsZero       0 1 2 -2 2
AwayFromZero      1 2 3 -3 3
NegativeInfinity  0 1 2 -3 2
PositiveInfinity  1 2 3 -2 3

The old integer constants PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN and PHP_ROUND_HALF_ODD still work as the third argument.

Rounding for display

round() gives you a number. To produce a string with a fixed number of decimals, use number_format() or sprintf():

<?php
$price = 1234567.891;
echo number_format($price), "\n";               // no decimals, comma thousands separator
echo number_format($price, 2), "\n";
echo number_format($price, 2, ',', '.'), "\n";  // European style
echo number_format(0.5), "\n";                  // rounds half away from zero
echo sprintf('%.2f', $price), "\n";
echo sprintf('%08.3f', 3.14159), "\n";          // zero padded, width 8
echo round(2.1, 2), "\n";                       // round() doesn't add trailing zeros

Output:

1,234,568
1,234,567.89
1.234.567,89
1
1234567.89
0003.142
2.1

For locale-aware formatting (currency symbols, Indian digit grouping, etc.) use NumberFormatter from the intl extension; see Localization.

Common functions

<?php
var_dump(abs(-5));
var_dump(abs(-5.5));
var_dump(max(3, 7, 2));
var_dump(max([3, 7, 2]));           // also accepts an array
var_dump(min(1.5, -2, 0));
var_dump(array_sum([1, 2, 3.5]));
var_dump(array_product([2, 3, 4]));
var_dump(sqrt(16));
var_dump(sqrt(2));
var_dump(pow(2, 10));               // same as 2 ** 10
var_dump(pow(4, 0.5));
var_dump(hypot(3, 4));              // sqrt(3*3 + 4*4)
var_dump(intdiv(17, 5), 17 % 5);

Output:

int(5)
float(5.5)
int(7)
int(7)
int(-2)
float(6.5)
int(24)
float(4)
float(1.4142135623730951)
int(1024)
float(2)
float(5)
int(3)
int(2)

PHP has no built-in clamp(); combine min() and max():

<?php
function clamp(int|float $value, int|float $min, int|float $max): int|float
{
    return max($min, min($max, $value));
}

var_dump(clamp(150, 0, 100));
var_dump(clamp(-3, 0, 100));
var_dump(clamp(0.25, 0.0, 1.0));

Output:

int(100)
int(0)
float(0.25)

Exponents and logarithms

<?php
var_dump(exp(1));          // e ** 1
var_dump(M_E);
var_dump(log(M_E));        // natural log
var_dump(log(8, 2));       // log with a base
var_dump(log10(1000));
var_dump(log(0));          // -INF
var_dump(log1p(1e-10));    // log(1 + x), accurate for tiny x
var_dump(expm1(1e-10));    // exp(x) - 1, accurate for tiny x
var_dump(sqrt(-1));        // NAN, no exception

Output:

float(2.718281828459045)
float(2.718281828459045)
float(1)
float(3)
float(3)
float(-INF)
float(9.999999999500001E-11)
float(1.00000000005E-10)
float(NAN)

There's no log2() function; use log($x, 2). To count bits of an integer exactly, avoid floats altogether: strlen(decbin($n)).

Trigonometry and constants

Trigonometric functions take and return radians. Convert with deg2rad() and rad2deg():

<?php
printf("pi      = %.15f\n", M_PI);
printf("sin 30  = %.4f\n", sin(deg2rad(30)));
printf("cos 60  = %.4f\n", cos(deg2rad(60)));
printf("tan 45  = %.4f\n", tan(M_PI_4));
printf("asin 1  = %.1f deg\n", rad2deg(asin(1)));
// atan2 handles all four quadrants and x == 0
printf("atan2   = %.1f deg\n", rad2deg(atan2(-1, -1)));
var_dump(sin(M_PI));   // not exactly 0

Output:

pi      = 3.141592653589793
sin 30  = 0.5000
cos 60  = 0.5000
tan 45  = 1.0000
asin 1  = 90.0 deg
atan2   = -135.0 deg
float(1.2246467991473532E-16)

Other useful constants: M_PI_2 (π/2), M_2_PI (2/π), M_SQRT2, M_SQRT1_2, M_LN2, M_LN10, M_LOG2E, M_LOG10E and M_EULER. pi() returns the same value as M_PI.

A practical example: distance between two points on Earth using the haversine formula:

<?php
function haversineKm(float $lat1, float $lon1, float $lat2, float $lon2): float
{
    $r = 6371.0; // mean Earth radius in km
    $dLat = deg2rad($lat2 - $lat1);
    $dLon = deg2rad($lon2 - $lon1);
    $a = sin($dLat / 2) ** 2
        + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dLon / 2) ** 2;
    return 2 * $r * asin(sqrt($a));
}

// Warsaw to Paris
printf("%.0f km\n", haversineKm(52.2297, 21.0122, 48.8566, 2.3522));

Output:

1367 km

Number bases

Integer literals can be written in decimal, hexadecimal (0x), octal (0o since PHP 8.1, or a leading 0) and binary (0b). Underscores can separate digits for readability:

<?php
var_dump(0xFF);
var_dump(0o17);
var_dump(017);
var_dump(0b1010);
var_dump(1_000_000);
var_dump(0xFF_FF);

Output:

int(255)
int(15)
int(15)
int(10)
int(1000000)
int(65535)

To convert at runtime, use dechex()/hexdec(), decoct()/octdec(), decbin()/bindec() and the general base_convert() (bases 2 to 36):

<?php
echo dechex(255), "\n";
echo hexdec('ff'), "\n";
echo decbin(10), "\n";
echo bindec('1010'), "\n";
echo decoct(8), "\n";
echo octdec('777'), "\n";
echo base_convert('zz', 36, 10), "\n";
echo base_convert('255', 10, 16), "\n";
echo str_pad(decbin(5), 8, '0', STR_PAD_LEFT), "\n";  // fixed width
echo sprintf('%08b %X %o', 5, 255, 8), "\n";          // or use sprintf
echo dechex(-1), "\n";                                // negative: two's complement

Output:

ff
255
1010
10
10
511
1295
ff
00000101
00000101 FF 10
ffffffffffffffff

Note that base_convert() works with floats internally and loses precision for large numbers. Use gmp_strval(gmp_init($s, $from), $to) for big values. For bit-level operations on integers see Bitwise Operators.

Infinity and NaN

Floats can hold three special values: INF, -INF and NAN. Check for them with is_finite(), is_infinite() and is_nan():

<?php
$values = [1.5, INF, -INF, NAN, 1e308 * 10, sqrt(-1)];
foreach ($values as $v) {
    printf("%-5s finite=%d infinite=%d nan=%d\n",
        var_export($v, true), is_finite($v), is_infinite($v), is_nan($v));
}
var_dump(NAN == NAN);   // NAN is not equal to anything, including itself
var_dump(INF > PHP_FLOAT_MAX);

Output:

1.5   finite=1 infinite=0 nan=0
INF   finite=0 infinite=1 nan=0
-INF  finite=0 infinite=1 nan=0
NAN   finite=0 infinite=0 nan=1
INF   finite=0 infinite=1 nan=0
NAN   finite=0 infinite=0 nan=1
bool(false)
bool(true)

Casting INF or NAN to int gives 0 (with a warning in PHP 8.5), so check before converting. Since NAN == NAN is false, in_array(NAN, $arr) never finds it; always use is_nan(). Before storing computed floats in a database or encoding them as JSON (where json_encode() fails on INF and NAN), check them with is_finite().

Comparing floats

Most decimal fractions can't be represented exactly in binary, so arithmetic accumulates tiny errors:

<?php
var_dump(0.1 + 0.2);
var_dump(0.1 + 0.2 == 0.3);
var_dump(floor((0.1 + 0.7) * 10));   // you might expect 8
printf("%.20f\n", 0.1);

Output:

float(0.30000000000000004)
bool(false)
float(7)
0.10000000000000000555

Never compare floats for exact equality after doing arithmetic. Compare with a tolerance instead. PHP_FLOAT_EPSILON is the smallest x such that 1.0 + x != 1.0, so it's suitable as a relative tolerance for values around 1. For arbitrary magnitudes scale the tolerance:

<?php
function floatEquals(float $a, float $b, float $relTol = 1e-9, float $absTol = 0.0): bool
{
    if ($a == $b) {
        return true; // also handles INF == INF
    }
    $diff = abs($a - $b);
    return $diff <= max($relTol * max(abs($a), abs($b)), $absTol);
}

var_dump(PHP_FLOAT_EPSILON);
var_dump(floatEquals(0.1 + 0.2, 0.3));
var_dump(floatEquals(1e20 + 1e4, 1e20));          // relative difference is tiny
var_dump(floatEquals(1e-12, 0.0));                // relative test fails near zero...
var_dump(floatEquals(1e-12, 0.0, absTol: 1e-9));  // ...so add an absolute tolerance

Output:

float(2.220446049250313E-16)
bool(true)
bool(true)
bool(false)
bool(true)

This is the same algorithm as Python's math.isclose(). For money, avoid floats entirely: store amounts as integer minor units (cents) or use BCMath with decimal strings.

Checking and converting numeric strings

Input from forms, files and databases arrives as strings. is_numeric() tells you whether a string looks like a number, and the arithmetic operators convert numeric strings automatically. Non-numeric strings throw TypeError in arithmetic:

<?php
foreach (['42', '-3.5', '1e3', ' 7', '7 ', '0x1A', 'abc', ''] as $s) {
    printf("%-6s %s\n", var_export($s, true), is_numeric($s) ? 'numeric' : 'not numeric');
}
var_dump('10' + 5);
var_dump('1.5' + 1);
try {
    var_dump('abc' * 2);
} catch (TypeError $e) {
    echo get_class($e), ": ", $e->getMessage(), "\n";
}

Output:

'42'   numeric
'-3.5' numeric
'1e3'  numeric
' 7'   numeric
'7 '   numeric
'0x1A' not numeric
'abc'  not numeric
''     not numeric
int(15)
float(2.5)
TypeError: Unsupported operand types: string * int

To validate user input as an integer or float with range checks, use filter_var() (see Validating An Integer Falls In A Range):

<?php
var_dump(filter_var('42', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 100]]));
var_dump(filter_var('420', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 100]]));
var_dump(filter_var('3.14', FILTER_VALIDATE_FLOAT));
var_dump(filter_var('3.14abc', FILTER_VALIDATE_FLOAT));

Output:

int(42)
bool(false)
float(3.14)
bool(false)

Simple statistics

PHP has no statistics module in the core, but the basics are short to write:

<?php
function mean(array $xs): float
{
    return array_sum($xs) / count($xs);
}

function median(array $xs): float
{
    sort($xs);
    $n = count($xs);
    $mid = intdiv($n, 2);
    return $n % 2 ? $xs[$mid] : ($xs[$mid - 1] + $xs[$mid]) / 2;
}

function stddev(array $xs): float
{
    $m = mean($xs);
    $sq = array_map(fn($x) => ($x - $m) ** 2, $xs);
    return sqrt(array_sum($sq) / (count($xs) - 1)); // sample standard deviation
}

$data = [2, 4, 4, 4, 5, 5, 7, 9];
printf("mean   %.3f\n", mean($data));
printf("median %.3f\n", median($data));
printf("stddev %.3f\n", stddev($data));
printf("range  %d..%d\n", min($data), max($data));

Output:

mean   5.000
median 4.500
stddev 2.138
range  2..9

GCD, LCM, factorial and primes

The core has no gcd() function. Euclid's algorithm is a one-liner, and the GMP extension provides fast versions of many number theory functions:

<?php
function gcd(int $a, int $b): int
{
    return $b === 0 ? abs($a) : gcd($b, $a % $b);
}

function lcm(int $a, int $b): int
{
    return intdiv(abs($a * $b), gcd($a, $b));
}

echo gcd(48, 18), " ", lcm(4, 6), "\n";

// with GMP
echo gmp_gcd(48, 18), " ", gmp_lcm(4, 6), "\n";
echo gmp_fact(25), "\n";                  // 25! doesn't fit in an int
echo gmp_nextprime(1000), "\n";
var_dump(gmp_prob_prime(2 ** 31 - 1));    // 2 = definitely prime, 1 = probably, 0 = composite

Output:

6 12
6 12
15511210043330985984000000
1009
int(1)

Arbitrary precision: GMP and BCMath

When integers exceed PHP_INT_MAX, or when decimal fractions must be exact, use one of the two arbitrary precision extensions. Both are bundled with PHP but must be enabled at compile time or installed as packages (php-gmp, php-bcmath).

GMP works with arbitrarily large integers. GMP objects support the normal arithmetic and comparison operators:

<?php
$a = gmp_init('123456789012345678901234567890');
$b = gmp_pow(2, 100);

var_dump($a * 2 > $b);
echo $a * 2, "\n";
echo $b, "\n";
echo $b % 1000, "\n";
echo gmp_strval($b, 16), "\n";   // in hex
echo gmp_sqrt($b), "\n";

Output:

bool(false)
246913578024691357802469135780
1267650600228229401496703205376
376
10000000000000000000000000
1125899906842624

BCMath works with decimal numbers represented as strings, with a precision (scale) you choose. That makes it suitable for money and other values where 0.1 + 0.2 must be exactly 0.3. PHP 8.4 added the BcMath\Number class, which is immutable and supports operators:

<?php
var_dump(bcadd('0.1', '0.2', 1));
var_dump(bcmul('19.99', '3', 2));
var_dump(bcdiv('10', '3', 5));          // truncated, not rounded
var_dump(bcround('2.675', 2));          // PHP 8.4+
var_dump(bcdiv('2', '3', 30));          // as many digits as you ask for

use BcMath\Number;

$price = new Number('19.99');
$qty = new Number('3');
$taxRate = new Number('0.23');

$net = $price * $qty;
$tax = ($net * $taxRate)->round(2);
$total = $net + $tax;

echo "net:   $net\n";
echo "tax:   $tax\n";
echo "total: $total\n";
var_dump($total > new Number('70'));

Output:

string(3) "0.3"
string(5) "59.97"
string(7) "3.33333"
string(4) "2.68"
string(32) "0.666666666666666666666666666666"
net:   59.97
tax:   13.79
total: 73.76
bool(true)

bcdiv() and the other functions truncate to the given scale; use bcround() or Number::round() when you want rounding. More BCMath examples are in BC Math Binary Calculator and Comparison between BCMath and float arithmetic operations.

Which one to choose:

Random numbers

For random integers and floats, use random_int() or Random\Randomizer. The details, including seeded generators and avoiding modulo bias, are in Random numbers.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents