Log in Sign up

Rounding

FunctionExampleResult
round($x)round(2.5)3 (half away from zero)
round($x, 2)round(3.14159, 2)3.14
floor($x)floor(4.9)4
ceil($x)ceil(4.1)5
abs($x)abs(-7)7

round, floor and ceil return a float – cast with (int) if you need an integer.

Basic math

Function / operatorExampleResult
min(...) / max(...)max(3, 9, 4)9
intdiv($a, $b)intdiv(7, 2)3
%7 % 31 (integer remainder)
fmod($a, $b)fmod(7.5, 2)1.5
** / pow()2 ** 101024
sqrt($x)sqrt(16)4.0
pi() / M_PI3.14159…
log($x), log10, explogarithms / e^x
sin, cos, tan, deg2rad, rad2degtrigonometry (radians)

Random numbers

FunctionUse
random_int(1, 6)cryptographically secure – use for tokens, codes, games
mt_rand(1, 6) / rand(1, 6)fast, not secure
random_bytes(16)secure random bytes, e.g. bin2hex(random_bytes(16))
array_rand($arr)random key of an array
lcg_value()float between 0 and 1

Formatting numbers

number_format(1234.5);                 // 1,235
number_format(1234.5, 2);              // 1,234.50
number_format(1234.5, 2, ',', '.');    // 1.234,50  (German style)
sprintf("%.1f%%", 45.678);             // 45.7%

Type conversion

MethodExampleResult
(int)$x / intval($x)(int)"42abc"42
(float)$x / floatval($x)(float)"3.5"3.5
(string)$x / strval($x)(string)42"42"
(bool)$x(bool)"0"false
is_numeric($x)is_numeric("1e3")true
filter_var($x, FILTER_VALIDATE_INT)"12a"false – best for user input

Number systems

FunctionExampleResult
dechex / hexdecdechex(255)ff
decbin / bindecdecbin(5)101
decoct / octdecdecoct(8)10
base_convert($n, from, to)base_convert("ff", 16, 2)11111111

Limits and float precision

  • PHP_INT_MAX – largest integer (9223372036854775807 on 64-bit); beyond it values become floats.
  • PHP_FLOAT_EPSILON – smallest difference between floats.
  • Floats are not exact: 0.1 + 0.2 == 0.3 is false. Compare with abs($a - $b) < PHP_FLOAT_EPSILON, or store money in cents as integers (or use the bcmath extension: bcadd("0.1", "0.2", 2)).

Previous: PHP Array Functions · Next: PHP Date and Time

Put together with AI as a quick reference I keep for my own work. Entries like this are usually not reviewed in detail by a person.