Math Functions
PHP's math functions live in the global namespace. They cover the calculator basics plus trig, logs, and number-system conversions.
Constants
| Constant | Value |
|---|---|
M_PI | 3.141592… (π) |
M_E | 2.718281… (e) |
M_SQRT2 | √2 |
INF / NAN | Infinity / not-a-number |
PHP_INT_MAX / PHP_INT_MIN | Platform int bounds |
PHP_FLOAT_EPSILON | Smallest positive distinguishable float |
Basics
| Function | Returns |
|---|---|
abs($x) | Absolute value. |
min(...) / max(...) | Smallest / largest (variadic). |
round($x, $d) / floor($x) / ceil($x) | Rounding. |
intdiv($a, $b) | Integer division. |
fmod($a, $b) | Float modulo. |
pow($x, $y) or $x ** $y | Power. |
sqrt($x) | Square root. |
Trig & logs
| Function | Returns |
|---|---|
sin / cos / tan / asin / acos / atan / atan2 | Trig (radians). |
deg2rad / rad2deg | Degrees ↔ radians. |
exp($x) | e^x. |
log($x, $base = M_E) / log10 / log2 | Logarithms. |
hypot($x, $y) | √(x² + y²). |
Random
| Function | Returns |
|---|---|
random_int(0, 100) | Cryptographically safe int. |
random_bytes(16) | 16 random bytes — for tokens. |
mt_rand($min, $max) | Fast PRNG — NOT for security. |
PHP 8.2+ \Random\Randomizer | Modern OO API; reseedable engines. |
Number-system conversions
| Function | Does |
|---|---|
dechex / hexdec | Decimal ↔ hex. |
decbin / bindec | Decimal ↔ binary. |
decoct / octdec | Decimal ↔ octal. |
base_convert($n, $from, $to) | Any-to-any (up to base 36). |
Tip: For money or anywhere you need exact decimals, skip
round / ceil / floor on floats — use bcadd / bcmul from the bcmath extension, or a brick/math library.Example
Example
<?php echo abs(-7), PHP_EOL; echo round(3.567, 2), PHP_EOL; echo ceil(3.1), floor(3.9), PHP_EOL; echo pow(2, 10), PHP_EOL; echo sqrt(16), PHP_EOL; echo rand(1, 6), PHP_EOL;Try it Yourself »
Exercise
Function for safe random integer.
(0, 100)
snake_case; 10 chars.
Discussion
Loading…