PHP Math Functions, Constants and Operators

Most of what you need for math in PHP is already part of the PHP core and no installation is required to use these features. Below are sections containing PHP math functions, constants and operators.

PHP Arithmetic Operators

Example
Name
Result
-$aNegationOpposite of $a.
$a + $bAdditionSum of $a and $b.
$a - $bSubtractionDifference of $a and $b.
$a * $bMultiplicationProduct of $a and $b.
$a / $bDivisionQuotient of $a and $b.
$a % $bModulusRemainder of $a divided by $b.

The division operator (“/”) returns a float value unless the two operands are integers (or strings that get converted to integers) and the numbers are evenly divisible, in which case an integer value will be returned.

Operands of modulus are converted to integers (by stripping the decimal part) before processing.

The result of the modulus operator % has the same sign as the dividend — that is, the result of $a % $b will have the same sign as $a. For example:

<?php

echo (5 % 3)."\n"; // prints 2
echo (5 % -3)."\n"; // prints 2
echo (-5 % 3)."\n"; // prints -2
echo (-5 % -3)."\n"; // prints -2

?>

PHP Math Constants

The constants below are always available as part of the PHP core.

Constant
Value
Description
Version
INFINFThe infinitePHP 4
M_E2.7182818284590452354Returns ePHP 4
M_EULER0.57721566490153286061Returns Euler constantPHP 4
M_LNPI1.14472988584940017414Returns the natural logarithm of PI: log_e(pi)PHP 5.2
M_LN20.69314718055994530942Returns the natural logarithm of 2: log_e 2PHP 4
M_LN102.30258509299404568402Returns the natural logarithm of 10: log_e 10PHP 4
M_LOG2E1.4426950408889634074Returns the base-2 logarithm of E: log_2 ePHP 4
M_LOG10E0.43429448190325182765Returns the base-10 logarithm of E: log_10 ePHP 4
M_PI3.14159265358979323846Returns PiPHP 4
M_PI_21.57079632679489661923Returns Pi/2PHP 4
M_PI_40.78539816339744830962Returns Pi/4PHP 4
M_1_PI0.31830988618379067154Returns 1/PiPHP 4
M_2_PI0.63661977236758134308Returns 2/PiPHP 4
M_SQRTPI1.77245385090551602729Returns the square root of PI: sqrt(pi)PHP 5.2
M_2_SQRTPI1.12837916709551257390Returns 2/square root of PI: 2/sqrt(pi)PHP 4
M_SQRT1_20.70710678118654752440Returns the square root of 1/2: 1/sqrt(2)PHP 4
M_SQRT21.41421356237309504880Returns the square root of 2: sqrt(2)PHP 4
M_SQRT31.73205080756887729352Returns the square root of 3: sqrt(3)PHP 5.2
NANNANNot A NumberPHP 4
PHP_ROUND_HALF_UP1Round halves upPHP 5.3
PHP_ROUND_HALF_DOWN2Round halves downPHP 5.3
PHP_ROUND_HALF_EVEN3Round halves to even numbersPHP 5.3
PHP_ROUND_HALF_ODD4Round halves to odd numbersPHP 5.3

PHP Math Function

PHP Math Introduction

The math functions can handle values within the range of integer and float types.

Installation

The PHP math functions are part of the PHP core. No installation is required to use these functions.

abs — Absolute value

number abs ( mixed $number )

Returns the absolute value of number.

<?php
$abs1 = abs(-3.2); // $abs = 3.2; (double/float)
$abs2 = abs(4); // $abs2 = 4; (integer)
$abs3 = abs(-4); // $abs3 = 4; (integer)
?>

acos — Arc cosine

float acos ( float $arg )

Returns the arc cosine of arg in radians. acos() is the complementary function of cos(), which means that a==cos(acos(a)) for every value of a that is within acos()’ range.

acosh — Inverse hyperbolic cosine

float acosh ( float $arg )

Returns the inverse hyperbolic cosine of arg, i.e. the value whose hyperbolic cosine is arg.

asin — Arc sine

float asin ( float $arg )

Returns the arc sine of arg in radians. asin() is the complementary function of sin(), which means that a==sin(asin(a)) for every value of a that is within asin()’s range.

asinh — Inverse hyperbolic sine

float asinh ( float $arg )

Returns the inverse hyperbolic sine of arg, i.e. the value whose hyperbolic sine is arg.

atan2 — Arc tangent of two variables

float atan2 ( float $y , float $x )

This function calculates the arc tangent of the two variables x and y. It is similar to calculating the arc tangent of y / x, except that the signs of both arguments are used to determine the quadrant of the result.

The function returns the result in radians, which is between -PI and PI (inclusive).

atan — Arc tangent

float atan ( float $arg )

Returns the arc tangent of arg in radians. atan() is the complementary function of tan(), which means that a==tan(atan(a)) for every value of a that is within atan()’s range.

atanh — Inverse hyperbolic tangent

float atanh ( float $arg )

Returns the inverse hyperbolic tangent of arg, i.e. the value whose hyperbolic tangent is arg.

base_convert — Convert a number between arbitrary bases

string base_convert ( string $number , int $frombase , int $tobase )

Returns a string containing number represented in base tobase. The base in which number is given is specified in frombase. Both frombase and tobase have to be between 2 and 36, inclusive. Digits in numbers with a base higher than 10 will be represented with the letters a-z, with a meaning 10, b meaning 11 and z meaning 35.

Note: base_convert() may lose precision on large numbers due to properties related to the internal “double” or “float” type used.

<?php
$hexadecimal = 'A37334';
echo base_convert($hexadecimal, 16, 2); // 101000110111001100110100
?>

bindec — Binary to decimal

number bindec ( string $binary_string )

Returns the decimal equivalent of the binary number represented by the binary_string argument.

bindec() converts a binary number to an integer or, if needed for size reasons, float.

bindec() interprets all binary_string values as unsigned integers. This is because bindec() sees the most significant bit as another order of magnitude rather than as the sign bit.

Note: The parameter must be a string. Using other data types will produce unexpected results.

<?php
echo bindec('110011') . "\n"; // 51
echo bindec('000110011') . "\n"; // 51

echo bindec('111'); // 7
?>

ceil — Round fractions up

float ceil ( float $value )

Returns the next highest integer value by rounding up value if necessary.

<?php
echo ceil(4.3); // 5
echo ceil(9.999); // 10
echo ceil(-3.14); // -3
?>

cos — Cosine

float cos ( float $arg )

cos() returns the cosine of the arg parameter. The arg parameter is in radians.

<?php
echo cos(M_PI); // -1
?>

cosh — Hyperbolic cosine

float cosh ( float $arg )

Returns the hyperbolic cosine of arg, defined as (exp(arg) + exp(-arg))/2.

decbin — Decimal to binary

string decbin ( int $number )

Returns a string containing a binary representation of the given number argument.

<?php
echo decbin(12) . "\n";
echo decbin(26);
?>

dechex — Decimal to hexadecimal

string dechex ( int $number )

Returns a string containing a hexadecimal representation of the given unsigned number argument.

<?php
echo dechex(10) . "\n";
echo dechex(47);
?>

decoct — Decimal to octal

string decoct ( int $number )

Returns a string containing an octal representation of the given number argument. The largest number that can be converted is 4294967295 in decimal resulting to “37777777777″.

<?php
echo decoct(15) . "\n";
echo decoct(264);
?>

deg2rad — Converts the number in degrees to the radian equivalent

float deg2rad ( float $number )

This function converts number from degrees to the radian equivalent.

<?php
echo deg2rad(45); // 0.785398163397
var_dump(deg2rad(45) === M_PI_4); // bool(true)
?>

exp — Calculates the exponent of e

float exp ( float $arg )

Returns e raised to the power of arg.

Note: ‘e’ is the base of the natural system of logarithms, or approximately 2.718282.

<?php
echo exp(12) . "\n";
echo exp(5.7);
?>

expm1 — Returns exp(number) – 1, computed in a way that is accurate even when the value of number is close to zero

float expm1 ( float $arg )

expm1() returns the equivalent to ‘exp(arg) – 1′ computed in a way that is accurate even if the value of arg is near zero, a case where ‘exp (arg) – 1′ would be inaccurate due to subtraction of two numbers that are nearly equal.

floor — Round fractions down

float floor ( float $value )

Returns the next lowest integer value by rounding down value if necessary.

<?php
echo floor(4.3); // 4
echo floor(9.999); // 9
echo floor(-3.14); // -4
?>

fmod — Returns the floating point remainder (modulo) of the division of the arguments

float fmod ( float $x , float $y )

Returns the floating point remainder of dividing the dividend (x) by the divisor (y). The reminder (r) is defined as: x = i * y + r, for some integer i. If y is non-zero, r has the same sign as x and a magnitude less than the magnitude of y.

<?php
$x = 5.7;
$y = 1.3;
$r = fmod($x, $y);
// $r equals 0.5, because 4 * 1.3 + 0.5 = 5.7
?>

getrandmax — Show largest possible random value

int getrandmax ( void )

Returns the maximum value that can be returned by a call to rand().

hexdec — Hexadecimal to decimal

number hexdec ( string $hex_string )

Returns the decimal equivalent of the hexadecimal number represented by the hex_string argument. hexdec() converts a hexadecimal string to a decimal number.

hexdec() will ignore any non-hexadecimal characters it encounters.

<?php
var_dump(hexdec("See"));
var_dump(hexdec("ee"));
// both print "int(238)"

var_dump(hexdec("that")); // print "int(10)"
var_dump(hexdec("a0")); // print "int(160)"
?>

hypot — Calculate the length of the hypotenuse of a right-angle triangle

float hypot ( float $x , float $y )

hypot() returns the length of the hypotenuse of a right-angle triangle with sides of length x and y, or the distance of the point (x, y) from the origin. This is equivalent to sqrt(x*x + y*y).

is_finite — Finds whether a value is a legal finite number

bool is_finite ( float $val )

Checks whether val is a legal finite on this platform. TRUE if val is a legal finite number within the allowed range for a PHP float on this platform, else FALSE.

is_infinite — Finds whether a value is infinite

bool is_infinite ( float $val )

Returns TRUE if val is infinite (positive or negative), like the result of log(0) or any value too big to fit into a float on this platform.

is_nan — Finds whether a value is not a number

bool is_nan ( float $val )

Checks whether val is ‘not a number’, like the result of acos(1.01).

<?php
// Invalid calculation, will return a NaN value
$nan = acos(8);

var_dump($nan, is_nan($nan));
?>

The above example will output:

float(NAN)
bool(true)

lcg_value — Combined linear congruential generator

float lcg_value ( void )

lcg_value() returns a pseudo random number in the range of (0, 1). The function combines two CGs with periods of 2^31 – 85 and 2^31 – 249. The period of this function is equal to the product of both primes.

log10 — Base-10 logarithm

float log10 ( float $arg )

Returns the base-10 logarithm of arg.

log1p — Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero

float log1p ( float $number )

log1p() returns log(1 + number) computed in a way that is accurate even when the value of number is close to zero. log() might only return log(1) in this case due to lack of precision.

log — Natural logarithm

float log ( float $arg [, float $base = M_E ] )

If the optional base parameter is specified, log() returns logbase arg, otherwise log() returns the natural logarithm of arg.

max — Find highest value

mixed max ( array $values )
mixed max ( mixed $value1 , mixed $value2 [, mixed $... ] )

If the first and only parameter is an array, max() returns the highest value in that array. If at least two parameters are provided, max() returns the biggest of these values.

Note: PHP will evaluate a non-numeric string as 0 if compared to integer, but still return the string if it’s seen as the numerically highest value. If multiple arguments evaluate to 0, max() will return a numeric 0 if given, else the alphabetical highest string value will be returned.

<?php
echo max(1, 3, 5, 6, 7); // 7
echo max(array(2, 4, 5)); // 5
?>

min — Find lowest value

mixed min ( array $values )
mixed min ( mixed $value1 , mixed $value2 [, mixed $... ] )

If the first and only parameter is an array, min() returns the lowest value in that array. If at least two parameters are provided, min() returns the smallest of these values.

Note: PHP will evaluate a non-numeric string as 0 if compared to integer, but still return the string if it’s seen as the numerically lowest value. If multiple arguments evaluate to 0, min() will return the lowest alphanumerical string value if any strings are given, else a numeric 0 is returned.

<?php
echo min(2, 3, 1, 6, 7); // 1
echo min(array(2, 4, 5)); // 2
?>

mt_getrandmax — Show largest possible random value

int mt_getrandmax ( void )

Returns the maximum value that can be returned by a call to mt_rand().

<?php
function randomFloat($min = 0, $max = 1) {
return $min + mt_rand() / mt_getrandmax() * ($max - $min);
}

var_dump(randomFloat());
var_dump(randomFloat(2, 20));
?>

The above example will output something similar to:

float(0.91601131712832)
float(16.511210331931)

mt_rand — Generate a better random value

int mt_rand ( void )
int mt_rand ( int $min , int $max )

Many random number generators of older libcs have dubious or unknown characteristics and are slow. By default, PHP uses the libc random number generator with the rand() function. The mt_rand() function is a drop-in replacement for this. It uses a random number generator with known characteristics using the » Mersenne Twister, which will produce random numbers four times faster than what the average libc rand() provides.

If called without the optional min, max arguments mt_rand() returns a pseudo-random value between 0 and mt_getrandmax(). If you want a random number between 5 and 15 (inclusive), for example, use mt_rand(5, 15).

<?php
echo mt_rand() . "\n"; // 1604716014
echo mt_rand() . "\n"; // 1478613278
echo mt_rand(5, 15); // 6
?>

mt_srand — Seed the better random number generator

void mt_srand ([ int $seed ] )

Seeds the random number generator with seed or with a random value if no seed is given.

Note: As of PHP 4.2.0, there is no need to seed the random number generator with srand() or mt_srand() as this is now done automatically.

<?php
// seed with microseconds
function make_seed()
{
list($usec, $sec) = explode(' ', microtime());
return (float) $sec + ((float) $usec * 100000);
}
mt_srand(make_seed());
$randval = mt_rand();
?>

octdec — Octal to decimal

number octdec ( string $octal_string )

Returns the decimal equivalent of the octal number represented by the octal_string argument.

<?php
echo octdec('77') . "\n"; // 63
echo octdec(decoct(45)); // 45
?>

pi — Get value of pi

float pi ( void )

Returns an approximation of pi. The returned float has a precision based on the precision directive in php.ini, which defaults to 14. Also, you can use the M_PI constant which yields identical results to pi().

<?php
echo pi(); // 3.1415926535898
echo M_PI; // 3.1415926535898
?>

pow — Exponential expression

number pow ( number $base , number $exp )

Returns base raised to the power of exp.

<?php
var_dump(pow(2, 8)); // int(256)
echo pow(-1, 20); // 1
echo pow(0, 0); // 1

echo pow(-1, 5.5); // PHP >4.0.6 NAN
echo pow(-1, 5.5); // PHP <=4.0.6 1.#IND
?>

rad2deg — Converts the radian number to the equivalent number in degrees

float rad2deg ( float $number )

This function converts number from radian to degrees.

<?php
echo rad2deg(M_PI_4); // 45
?>

rand — Generate a random integer

int rand ( void )
int rand ( int $min , int $max )

If called without the optional min, max arguments rand() returns a pseudo-random integer between 0 and getrandmax(). If you want a random number between 5 and 15 (inclusive), for example, use rand(5, 15).

Note: On some platforms (such as Windows), getrandmax() is only 32767. If you require a range larger than 32767, specifying min and max will allow you to create a range larger than this, or consider using mt_rand() instead.

<?php
echo rand() . "\n"; // 7771
echo rand() . "\n"; // 22264
echo rand(5, 15); // 11
?>

round — Rounds a float

float round ( float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] )

Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).

Note: PHP doesn’t handle strings like “12,300.2″ correctly by default. See converting from strings.

<?php
echo round(3.4); // 3
echo round(3.5); // 4
echo round(3.6); // 4
echo round(3.6, 0); // 4
echo round(1.95583, 2); // 1.96
echo round(1241757, -3); // 1242000
echo round(5.045, 2); // 5.05
echo round(5.055, 2); // 5.06
?>

sin — Sine

float sin ( float $arg )

sin() returns the sine of the arg parameter. The arg parameter is in radians.

<?php

// Precision depends on your precision directive
echo sin(deg2rad(60)); // 0.866025403 ...
echo sin(60); // -0.304810621 ...

?>

sinh — Hyperbolic sine

float sinh ( float $arg )

Returns the hyperbolic sine of arg, defined as (exp(arg) – exp(-arg))/2.

sqrt — Square root

float sqrt ( float $arg )

Returns the square root of arg.

<?php
// Precision depends on your precision directive
echo sqrt(9); // 3
echo sqrt(10); // 3.16227766 ...
?>

srand — Seed the random number generator

void srand ([ int $seed ] )

Seeds the random number generator with seed or with a random value if no seed is given.

Note: As of PHP 4.2.0, there is no need to seed the random number generator with srand() or mt_srand() as this is now done automatically.

<?php
// seed with microseconds
function make_seed()
{
list($usec, $sec) = explode(' ', microtime());
return (float) $sec + ((float) $usec * 100000);
}
srand(make_seed());
$randval = rand();
?>

tan — Tangent

float tan ( float $arg )

tan() returns the tangent of the arg parameter. The arg parameter is in radians.

<?php

echo tan(M_PI_4); // 1

?>

tanh — Hyperbolic tangent

float tanh ( float $arg )

Returns the hyperbolic tangent of arg, defined as sinh(arg)/cosh(arg).

Share This Post

Recent Articles

Leave a Reply