PHP Math

PHP provides a comprehensive set of math functions, built into the core of the language, which allow you to perform basic arithmetic, trigonometry, random number generation, rounding, and more. Here's an overview of common PHP math functions:


Basic Arithmetic

PHP uses standard operators for arithmetic:

$a + $b // Addition $a - $b // Subtraction $a * $b // Multiplication $a / $b // Division $a % $b // Modulus

Common Math Functions

Function Description
abs($x) Absolute value of $x
ceil($x) Rounds $x up to the nearest integer
floor($x) Rounds $x down to the nearest integer
round($x) Rounds $x to the nearest integer
max($a, $b, ...) Returns the highest value
min($a, $b, ...) Returns the lowest value
pow($x, $y) Raises $x to the power of $y
sqrt($x) Square root of $x

Rounding Variants

round(4.3); // 4 round(4.6); // 5 round(4.5); // 5 round(4.567, 2); // 4.57

Random Numbers

rand(); // Random int rand(1, 10); // Random int between 1 and 10 mt_rand(1, 100); // Better random number generator

Trigonometry (uses radians)

sin($x); cos($x); tan($x); asin($x); acos($x); atan($x);

???? Other Useful Math Functions

exp($x); // e raised to the power of $x log($x); // Natural logarithm log10($x); // Base-10 logarithm deg2rad($x); // Degrees to radians rad2deg($x); // Radians to degrees