iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

ConstantValue
M_PIπ
M_Ee
PHP_INT_MAX / PHP_INT_MINPlatform int bounds
PHP_FLOAT_EPSILONSmallest positive float resolvable
INF, NANInfinity / not-a-number

Common functions

FunctionReturns
abs($x)Absolute value
floor / ceil / roundRounding
min(...) / max(...)Extremes (variadic)
sqrt($x)Square root
pow($x, $y) or $x ** $yPower
exp / log / log10Exponential & logarithm
sin / cos / tan / asin / acos / atanTrig (radians)
deg2rad / rad2degDegree ↔ 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 ;

Test yourself

Q1. π constant is…
Q2. Float-safe equality test…
Q3. For money decimals use…

Discussion

Loading…