Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 147 ยท Data Types

Math Functions

Learn PHP math functions - abs, round with PHP 8.4 rounding modes, floor, ceil, min, max, powers, random_int, number_format and bcmath for exact money math.

PHP comes with a large set of built-in math functions, and you don't need to import or install anything to use them. They cover everything a typical web application needs: rounding prices, finding the biggest value in a list, picking a random winner, formatting 1234567.5 as 1,234,567.50, and (with the bcmath extension) doing exact decimal arithmetic so your invoice totals are never off by a cent.

This lesson tours the functions you'll use most, grouped by job. Along the way you'll see which ones return integers and which return floats (it's not always obvious), how PHP 8.4 made rounding more flexible with the RoundingMode enum, why rand() is the wrong choice for anything security-related, and how to handle money correctly.

You should be comfortable with the material in Integers and Floats, especially float precision, before reading on.

Absolute value, minimum and maximum

abs() removes the sign of a number. It keeps the type: an int stays an int, a float stays a float. min() and max() accept either several arguments or a single array:

PHP abs, min and max

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

min() and max() compare values with PHP's normal comparison rules, so they also work on strings (alphabetical order, byte by byte) and return the original value with its original type. Mixing types in one call works but makes results hard to predict, so keep lists homogeneous.

Calling min([]) or max([]) with an empty array throws a ValueError (min(): Argument #1 ($value) must contain at least one element). If a list can be empty, check count($list) > 0 first or provide a fallback.

Rounding: round, floor and ceil

These three functions turn a number with a fractional part into a rounder one:

Function What it does 2.5 -2.5 2.1
round($n) Nearest whole number, halves away from zero 3 -3 2
floor($n) Down, toward negative infinity 2 -3 2
ceil($n) Up, toward positive infinity 3 -2 3

All three return a float, even when the result is a whole number, because the result might be too large for an int. Cast with (int) when you need an integer, for example for an array index or a page number.

round() takes an optional precision: the number of decimal places to keep. A negative precision rounds to tens, hundreds and so on:

PHP round, floor and ceil

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output starts with float(3.14), float(1200) and float(7). The page calculation is a classic use of ceil(): 47 items at 10 per page need 5 pages, not 4.7. The minutes example shows floor() together with % to split a duration.

Rounding works on the float's real binary value, so a number like 1.955 (stored as something very slightly below 1.955) is tricky. PHP 8.4 improved round() to give the answer people expect in these cases, so round(1.955, 2) is 1.96 and round(5.045, 2) is 5.05. Older PHP versions could return 1.95 and 5.04. For money, though, don't rely on float rounding at all: use integer cents or bcmath, as shown at the end of this lesson.

Rounding modes (PHP 8.4)

By default, round() rounds halves away from zero: 2.5 becomes 3 and -2.5 becomes -3. That's what most people learned in school, but finance and statistics often use other rules. The third parameter chooses the mode. Since PHP 8.4, you pass a case of the RoundingMode enum:

RoundingMode case Rule 2.5 3.5 -2.5
HalfAwayFromZero (default) Halves go away from zero 3 4 -3
HalfTowardsZero Halves go toward zero 2 3 -2
HalfEven Halves go to the even neighbor ("banker's rounding") 2 4 -2
HalfOdd Halves go to the odd neighbor 3 3 -3
TowardsZero Always toward zero (truncate) 2 3 -2
AwayFromZero Always away from zero 3 4 -3
NegativeInfinity Always down (like floor) 2 3 -3
PositiveInfinity Always up (like ceil) 3 4 -2

The last four modes round every value, not just halves, and they work with a precision, which floor() and ceil() don't:

PHP Rounding modes in PHP 8.4

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Banker's rounding sends half of the halves up and half down, so totals don't drift upward: the original values sum to 16, normal rounding gives 18, and HalfEven gives exactly 16. (The fn ($v) => ... syntax is an arrow function, explained in Anonymous Functions and Closures.)

Before PHP 8.4, the modes were integer constants: PHP_ROUND_HALF_UP (the default), PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN and PHP_ROUND_HALF_ODD. They still work, so you'll see round($x, 2, PHP_ROUND_HALF_EVEN) in existing code.

Powers, roots and other functions

PHP has an operator for powers, ** (PHP 5.6+), and the older function pow(), which does the same thing. Integer powers stay integers as long as the result fits; negative or fractional exponents give floats:

PHP
var_dump(2 ** 10);        // int(1024)
var_dump(pow(2, 10));     // int(1024)
var_dump(2 ** -1);        // float(0.5)
var_dump(10 ** 20);       // float(1.0E+20): too big for an int
var_dump(sqrt(16));       // float(4)
var_dump(sqrt(-1));       // float(NAN)
var_dump(hypot(3, 4));    // float(5): sqrt(3**2 + 4**2)

Here's a reference of the other common math functions. All of them return floats except where noted:

Function Purpose Example
sqrt($n) Square root sqrt(2) is 1.4142135623730951
intdiv($a, $b) Integer division (returns int) intdiv(10, 3) is 3
fmod($a, $b) Float remainder fmod(10, 3) is 1.0
exp($n), log($n) en, natural log log(M_E) is 1.0
log($n, $base) Log in any base log(8, 2) is 3.0
log10($n) Base-10 log log10(1000) is 3.0
sin, cos, tan, atan2 Trigonometry, in radians sin(M_PI / 2) is 1.0
deg2rad, rad2deg Convert angles deg2rad(180) is M_PI
pi() or M_PI ฯ€ 3.141592653589793
array_sum, array_product Sum or product of an array array_sum([1, 2, 3.5]) is 6.5

Converting between number bases

Four functions convert integers to and from other bases. They work with strings for the non-decimal side:

PHP Number bases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

base_convert() handles any base from 2 to 36 (using letters a to z for digits above 9). The last example splits a hex color into pairs and converts each one, a common task when working with CSS or images. The [$r, $g, $b] = ... syntax unpacks an array into variables; see Destructuring and Spread.

Random numbers

For random integers, use random_int($min, $max). Both ends are included, and the numbers come from the operating system's cryptographically secure generator, so they're safe for anything: dice, shuffling, verification codes, tokens.

PHP Secure random numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Run it a few times: the output changes every time. Note the str_pad() call: random_int(0, 999_999) can return 4217, which must become 004217 to be a six-digit code.

The older functions rand() and mt_rand() are not secure: their output can be predicted once someone sees a few values. Never use them for passwords, tokens, reset links or anything an attacker might want to guess. Since PHP 8.2, the object-oriented Random\Randomizer class gives you secure random floats, shuffles and strings as well; it's covered in Hashing, Encryption and Random Numbers.

Formatting numbers for people

number_format() adds thousands separators and fixes the number of decimals. It returns a string, so do all your math first and format only for display:

PHP number_format for display

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output:

TEXT
1,234,568
1,234,567.89
1.234.567,89
1 234 567.89
1234568
1,200
0

The third and fourth arguments are the decimal point and the thousands separator, which lets you match conventions like German (1.234.567,89) or French (1 234 567,89). A negative precision (PHP 8.3+) rounds to tens or hundreds. And since PHP 8.0, number_format(-0.4) prints 0, not -0. For full locale-aware formatting, PHP has the intl extension's NumberFormatter (not installed on our server), and Formatting Strings covers sprintf() and printf().

Hyperbolic functions and precise small values

Besides sin, cos and tan, PHP has the hyperbolic family: sinh(), cosh() and tanh() and their inverses asinh(), acosh() and atanh(). They appear in physics (a hanging cable follows cosh), in statistics and in neural networks (tanh is a classic activation function). Mind the domains: acosh($x) needs $x >= 1 and atanh($x) needs a value strictly between -1 and 1, or you get NAN/INF.

Two other helpers exist for accuracy. expm1($x) computes exp($x) - 1 and log1p($x) computes log(1 + $x). For tiny $x the naive form loses digits because 1 + 0.0000000001 rounds before the subtraction; these functions avoid that. They matter in finance (small interest rates) and science.

And atan2($y, $x) deserves a place in your toolbox: unlike atan($y / $x) it knows which quadrant the point is in, so it gives the correct angle for any direction. Together with hypot($x, $y) (the length of the vector, without overflow) it converts rectangular coordinates to polar ones.

PHP Hyperbolic functions, expm1 and atan2

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last loop shows why atan2() exists: for (-1, 1) and (1, -1) plain atan() gives the same -45 degrees even though the points are opposite each other. Everything about angles uses radians; convert with rad2deg() and deg2rad() as in the table above.

Exact decimal math with bcmath

Floats can't store most decimal fractions exactly, so 0.1 + 0.7 is really 0.7999999999999999, and floor((0.1 + 0.7) * 10) gives 7, not 8. For money, that's not acceptable. You have two good options:

  1. Integer cents. Store 19.99 as 1999. Integer addition and multiplication are exact. Convert to a decimal string only for display.
  2. The bcmath extension. It does arithmetic on numbers written as strings, with as many decimal places as you ask for, and never rounds behind your back.

bcmath functions take string operands and an optional scale (the number of decimal places in the result). Extra digits are cut off, not rounded, so pick a scale with enough room, then round deliberately with bcround() (PHP 8.4+):

PHP Exact money math with bcmath

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The subtotal is exactly 59.97, the tax 4.9475, and bcround() rounds the total 64.9175 to 64.92. bccomp() compares two numbers and returns -1, 0 or 1 (here 0: they're equal). bcpow('2', '100') shows that bcmath also handles integers far beyond PHP_INT_MAX.

BcMath\Number (PHP 8.4)

Calling a function for every operation gets wordy. PHP 8.4 added the BcMath\Number class, which supports the normal arithmetic operators and works out the scale for you:

PHP
use BcMath\Number;

$price = new Number('19.99');
$total = $price * 3 + new Number('0.015');

echo $total;          // 59.985
echo $total->scale;   // 3

Number objects are immutable; each operation returns a new one. For arbitrarily large integers (factorials, cryptography), there's also the gmp extension: gmp_strval(gmp_fact(25)) gives 15511210043330985984000000.

Number theory with GMP

The gmp extension (GNU Multiple Precision) works on integers of any size and has a whole number-theory toolbox that bcmath lacks. Numbers go in as ints or numeric strings and come out as GMP objects, which support the normal operators (+ - * / % **) and are printed with gmp_strval().

  • gmp_gcd(), gmp_lcm() and gmp_gcdext(): the extended Euclid algorithm returns g, s and t with a*s + b*t = g.
  • gmp_invert($a, $m): the modular inverse (the x with a*x โ‰ก 1 mod m), or false when none exists.
  • gmp_powm($base, $exp, $mod): fast modular exponentiation, the engine of RSA-style algorithms.
  • gmp_nextprime($n), gmp_prob_prime($n): the next prime above n, and a probabilistic primality test returning 0 (composite), 1 (probably prime) or 2 (definitely prime).
  • gmp_jacobi() and gmp_legendre(): symbols that tell whether a number is a square modulo a prime (1) or not (-1).
  • gmp_root() / gmp_rootrem() and gmp_sqrt(): integer roots.
  • gmp_popcount(), gmp_hamdist(), gmp_and(), gmp_or(), gmp_xor(), gmp_setbit(), gmp_testbit(): bit counting and bit operations on huge numbers.
PHP GMP number theory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The toy RSA above only demonstrates modular arithmetic. For real encryption use openssl_* or libsodium as described in Cryptography; never invent your own scheme.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does var_dump(floor(7.8)); print?

    floor, ceil and round always return floats, even when the result is a whole number. Cast with (int) when you need an integer.
  2. 2. What is round(-2.5) with the default rounding mode?

    The default mode rounds halves away from zero, so -2.5 becomes -3. RoundingMode::HalfEven would give -2.
  3. 3. 47 search results are shown 10 per page. Which expression gives the number of pages?

    You need a page for the last 7 results too, so you must round up. ceil(4.7) is 5; the others give 4 or 5 only by accident.
  4. 4. Which function should you use to generate a password reset code?

    random_int uses a cryptographically secure source. rand and mt_rand are predictable, and the time is trivial to guess.
  5. 5. What does bcadd('0.1', '0.2', 1) return?

    bcmath works on decimal strings and returns a string with exactly the requested scale (1 decimal place), with no binary float error.

Summary

  • abs() keeps the type; min() and max() accept several values or an array, and throw ValueError on an empty array.
  • round(), floor() and ceil() return floats. round() takes a precision (negative for tens and hundreds) and, since PHP 8.4, a RoundingMode such as HalfEven.
  • ** (or pow()) raises to a power; sqrt(), log(), trigonometry and base conversion (dechex, bindec, base_convert) are all built in.
  • Use random_int() for random integers; rand() and mt_rand() are predictable.
  • number_format() formats numbers for display and returns a string.
  • For money, use integer cents or bcmath string math (bcadd, bcmul, bcround, BcMath\Number in PHP 8.4). Never floats.

Next: Arithmetic and Assignment Operators