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

Math Functions

PHP's math functions live in the global namespace. They cover the calculator basics plus trig, logs, and number-system conversions.

Constants

ConstantValue
M_PI3.141592… (π)
M_E2.718281… (e)
M_SQRT2√2
INF / NANInfinity / not-a-number
PHP_INT_MAX / PHP_INT_MINPlatform int bounds
PHP_FLOAT_EPSILONSmallest positive distinguishable float

Basics

FunctionReturns
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 ** $yPower.
sqrt($x)Square root.

Trig & logs

FunctionReturns
sin / cos / tan / asin / acos / atan / atan2Trig (radians).
deg2rad / rad2degDegrees ↔ radians.
exp($x)e^x.
log($x, $base = M_E) / log10 / log2Logarithms.
hypot($x, $y)√(x² + y²).

Random

FunctionReturns
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\RandomizerModern OO API; reseedable engines.

Number-system conversions

FunctionDoes
dechex / hexdecDecimal ↔ hex.
decbin / bindecDecimal ↔ binary.
decoct / octdecDecimal ↔ 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)

Test yourself

Q1. M_PI is the value of…
Q2. Cryptographically safe int is…
Q3. For exact decimals use…

Discussion

Loading…