PHP Math
PHP's math functions are in the global namespace — no import needed. Covers the calculator basics, plus trig, logs, and a few specials.
Constants
| Constant | Value |
|---|---|
M_PI | π |
M_E | e |
PHP_INT_MAX / PHP_INT_MIN | Platform int bounds |
PHP_FLOAT_EPSILON | Smallest positive float resolvable |
INF, NAN | Infinity / not-a-number |
Common functions
| Function | Returns |
|---|---|
abs($x) | Absolute value |
floor / ceil / round | Rounding |
min(...) / max(...) | Extremes (variadic) |
sqrt($x) | Square root |
pow($x, $y) or $x ** $y | Power |
exp / log / log10 | Exponential & logarithm |
sin / cos / tan / asin / acos / atan | Trig (radians) |
deg2rad / rad2deg | Degree ↔ radian |
fmod($x, $y) | Float modulo |
intdiv($x, $y) | Integer division |
is_nan($x) / is_infinite($x) / is_finite($x) | Special value tests |
Random
PHP
random_int(1, 100); // cryptographically safe random_bytes(16); // 16 random bytes (for tokens) // PHP 8.2+ Randomizer $rng = new \Random\Randomizer(); $rng->getInt(1, 100); $rng->shuffleArray([1, 2, 3, 4]);
Tip: Don't compare floats with
==. Use abs($a - $b) < PHP_FLOAT_EPSILON or pick a tolerance you care about.Example
Example
<?php echo PI, PHP_EOL; echo sqrt(16), PHP_EOL; echo round(3.567, 2), PHP_EOL; echo min(3, 1, 2), max(3, 1, 2), PHP_EOL; echo abs(-7), PHP_EOL;Try it Yourself »
Exercise
PHP constant for π.
echo
;
Four characters; starts with M_.
Discussion
Loading…