PHP provides built-in math functions to perform various numerical operations like arithmetic, rounding, random number generation, and trigonometry.
Functions like abs()
, pow()
, sqrt()
, and round()
help in basic calculations.
You can also generate random values using rand()
or random_int()
.
Advanced functions include sin()
, log()
, exp()
, and number formatting with number_format()
.
These are useful in real-world tasks like billing, statistics, games, or calculators.
File Name: math-functions.php
1. Basic Arithmetic
echo abs(-10); // ➤ 10
echo pow(2, 3); // ➤ 8 (2^3)
echo sqrt(16); // ➤ 4
echo max(3, 7, 1); // ➤ 7
echo min(3, 7, 1); // ➤ 1
2. Rounding Functions
echo round(3.6); // ➤ 4
echo floor(3.6); // ➤ 3
echo ceil(3.2); // ➤ 4
3. Random Numbers
echo rand(); // ➤ Random number
echo rand(100, 999); // ➤ Random between 100 and 999
Use random_int(1, 10)
for cryptographically secure random numbers (PHP 7+)
4. Trigonometric Functions
echo sin(deg2rad(30)); // ➤ 0.5
echo cos(deg2rad(60)); // ➤ 0.5
echo tan(deg2rad(45)); // ➤ 1
5. Logarithmic and Exponential
echo log(10); // ➤ Natural log
echo log10(1000); // ➤ Base-10 log ➝ 3
echo exp(1); // ➤ e^1 ➝ ~2.718
6. Number Formatting
echo number_format(1234567.89); // ➤ 1,234,567.89
echo number_format(1234.56, 2, '.', ','); // ➤ 1,234.56
Summary Table
Function | Purpose |
---|---|
abs() |
Absolute value |
pow(x, y) |
Power of x to y |
sqrt() |
Square root |
round() |
Round to nearest integer |
floor() |
Round down |
ceil() |
Round up |
rand() |
Random number |
max()/min() |
Find highest/lowest value |
sin()/cos() |
Trigonometric functions |
log()/exp() |
Logarithmic & exponential |
number_format() |
Format number for display |