PHP Math Functions

PHP Math Functions

PHP includes a full library of mathematical functions for calculations, rounding, and random number generation.

1 - Basic Math

abs(-7);          // 7
ceil(4.2);        // 5  — round up
floor(4.9);       // 4  — round down
round(4.5);       // 5
round(4.567, 2);  // 4.57
sqrt(16);         // 4
pow(2, 10);       // 1024
max(1, 5, 3);     // 5
min(1, 5, 3);     // 1
intdiv(7, 2);     // 3  — integer division (PHP 7+)
fmod(7.5, 2);     // 1.5 — float modulo

2 - Random Numbers

rand(1, 100);         // random integer 1-100
mt_rand(1, 100);      // faster Mersenne Twister
random_int(1, 100);   // cryptographically secure (PHP 7+)

3 - Constants

M_PI;         // 3.14159265358979...
M_E;          // 2.71828182845905...
PHP_INT_MAX;  // 9223372036854775807
PHP_FLOAT_MAX; // 1.7976931348623E+308

4 - Number Formatting

number_format(1234567.891, 2, ".", ",");
// "1,234,567.89"

// Locale-aware
setlocale(LC_MONETARY, "en_US");
money_format("%.2n", 1234.56); // "$1,234.56"

Note: Use random_int() instead of rand() whenever security matters — e.g. generating tokens, OTPs, or passwords. rand() is not cryptographically secure.

-Tip-