PHP Math
Mathematical functions and operations in PHP
🔢 What is PHP Math?
PHP provides extensive mathematical functions for calculations, from basic arithmetic to advanced operations like trigonometry, logarithms, and random number generation. These functions help you build calculators, games, and data analysis tools.
<?php
// Simple math operations
echo abs(-15); // Absolute value
echo " | ";
echo sqrt(16); // Square root
echo " | ";
echo pow(2, 3); // Power
?>
Output:
Math Function Categories
Basic Operations
Fundamental math functions
Advanced Math
Complex calculations
Random Numbers
Generate random values
Trigonometry
Angle and triangle functions
🔹 Basic Math Functions
PHP's basic math functions handle common operations like absolute values, rounding, and finding minimum/maximum values. These are essential for everyday calculations.
<?php
// Absolute value
echo "abs(-42): " . abs(-42) . "\n";
// Rounding
echo "round(4.7): " . round(4.7) . "\n";
echo "round(4.3): " . round(4.3) . "\n";
// Ceiling (round up)
echo "ceil(4.1): " . ceil(4.1) . "\n";
// Floor (round down)
echo "floor(4.9): " . floor(4.9) . "\n";
// Min and Max
echo "min(2, 5, 1, 8): " . min(2, 5, 1, 8) . "\n";
echo "max(2, 5, 1, 8): " . max(2, 5, 1, 8);
?>
Output:
round(4.7): 5
round(4.3): 4
ceil(4.1): 5
floor(4.9): 4
min(2, 5, 1, 8): 1
max(2, 5, 1, 8): 8
🔹 Power and Root Functions
Calculate powers, square roots, and cube roots with PHP's exponential functions. These are useful for scientific calculations and geometric formulas.
<?php
// Power (base, exponent)
echo "pow(2, 3): " . pow(2, 3) . "\n";
echo "pow(5, 2): " . pow(5, 2) . "\n";
// Square root
echo "sqrt(16): " . sqrt(16) . "\n";
echo "sqrt(25): " . sqrt(25) . "\n";
// Cube root (using pow)
echo "Cube root of 27: " . pow(27, 1/3) . "\n";
// Exponential (e^x)
echo "exp(1): " . round(exp(1), 2) . "\n";
// Natural logarithm
echo "log(10): " . round(log(10), 2);
?>
Output:
pow(5, 2): 25
sqrt(16): 4
sqrt(25): 5
Cube root of 27: 3
exp(1): 2.72
log(10): 2.3
🔹 Random Number Generation
Generate random numbers for games, simulations, and security. Use random_int() for cryptographically secure random numbers, or rand() for general purposes.
<?php
// Basic random number (0 to max)
echo "rand(): " . rand() . "\n\n";
// Random in range
echo "rand(1, 10): " . rand(1, 10) . "\n";
echo "rand(1, 10): " . rand(1, 10) . "\n\n";
// Better random (Mersenne Twister)
echo "mt_rand(1, 100): " . mt_rand(1, 100) . "\n\n";
// Cryptographically secure random
echo "random_int(1, 6): " . random_int(1, 6) . "\n";
// Random float between 0 and 1
echo "Random float: " . (mt_rand() / mt_getrandmax());
?>
Output:
rand(1, 10): 7
rand(1, 10): 3
mt_rand(1, 100): 42
random_int(1, 6): 4
Random float: 0.846532
🔹 Rounding with Precision
Control decimal precision when rounding numbers. Specify how many decimal places to keep, or round to the nearest multiple of a number.
<?php
$number = 3.14159;
// Round to different decimal places
echo "Original: $number\n";
echo "round($number, 0): " . round($number, 0) . "\n";
echo "round($number, 2): " . round($number, 2) . "\n";
echo "round($number, 4): " . round($number, 4) . "\n\n";
// Round to nearest 5
$price = 47;
echo "Round $price to nearest 5: " . (round($price / 5) * 5) . "\n";
// Round to nearest 10
echo "Round $price to nearest 10: " . (round($price / 10) * 10);
?>
Output:
round(3.14159, 0): 3
round(3.14159, 2): 3.14
round(3.14159, 4): 3.1416
Round 47 to nearest 5: 45
Round 47 to nearest 10: 50
🔹 Trigonometric Functions
PHP includes all standard trigonometric functions for working with angles. Remember that PHP uses radians, not degrees, so convert when necessary.
<?php
// Convert degrees to radians
$degrees = 45;
$radians = deg2rad($degrees);
echo "Angle: $degrees degrees\n\n";
// Trigonometric functions
echo "sin($degrees°): " . round(sin($radians), 2) . "\n";
echo "cos($degrees°): " . round(cos($radians), 2) . "\n";
echo "tan($degrees°): " . round(tan($radians), 2) . "\n\n";
// Inverse functions
echo "asin(0.5): " . round(rad2deg(asin(0.5)), 2) . "°\n";
echo "acos(0.5): " . round(rad2deg(acos(0.5)), 2) . "°\n";
// Pi constant
echo "\nPI: " . M_PI;
?>
Output:
sin(45°): 0.71
cos(45°): 0.71
tan(45°): 1
asin(0.5): 30°
acos(0.5): 60°
PI: 3.14159265359
🔹 Number Formatting
Format numbers for display with thousands separators and decimal places. This makes large numbers more readable and ensures consistent decimal precision.
<?php
$number = 1234567.89;
// Format with 2 decimals
echo "number_format($number, 2): " . number_format($number, 2) . "\n\n";
// Custom separators (decimals, decimal_sep, thousands_sep)
echo "US format: " . number_format($number, 2, '.', ',') . "\n";
echo "EU format: " . number_format($number, 2, ',', '.') . "\n\n";
// Currency formatting
$price = 1999.99;
echo "Price: $" . number_format($price, 2) . "\n";
// Percentage
$percent = 0.1567;
echo "Percentage: " . number_format($percent * 100, 1) . "%";
?>
Output:
US format: 1,234,567.89
EU format: 1.234.567,89
Price: $1,999.99
Percentage: 15.7%
🔹 Math Constants
PHP provides predefined mathematical constants for common values. These are more accurate than manually typing decimal approximations.
<?php
// Pi
echo "M_PI: " . M_PI . "\n";
// Euler's number
echo "M_E: " . M_E . "\n";
// Square root of 2
echo "M_SQRT2: " . M_SQRT2 . "\n";
// Natural log of 2
echo "M_LN2: " . M_LN2 . "\n";
// Log base 10 of E
echo "M_LOG10E: " . M_LOG10E . "\n\n";
// Calculate circle area
$radius = 5;
$area = M_PI * pow($radius, 2);
echo "Circle area (r=$radius): " . round($area, 2);
?>
Output:
M_E: 2.71828182846
M_SQRT2: 1.41421356237
M_LN2: 0.69314718056
M_LOG10E: 0.43429448190
Circle area (r=5): 78.54
🔹 Practical Math Examples
Real-world applications of PHP math functions in common programming scenarios like calculating percentages, averages, and distances.
<?php
// Calculate percentage
function percentage($part, $total) {
return round(($part / $total) * 100, 1);
}
echo "75 out of 200: " . percentage(75, 200) . "%\n\n";
// Calculate average
$scores = [85, 92, 78, 95, 88];
$average = array_sum($scores) / count($scores);
echo "Average score: " . round($average, 1) . "\n\n";
// Distance between two points
function distance($x1, $y1, $x2, $y2) {
return sqrt(pow($x2 - $x1, 2) + pow($y2 - $y1, 2));
}
echo "Distance (0,0) to (3,4): " . distance(0, 0, 3, 4) . "\n\n";
// Compound interest
$principal = 1000;
$rate = 0.05;
$years = 5;
$amount = $principal * pow(1 + $rate, $years);
echo "Investment after $years years: $" . round($amount, 2);
?>
Output:
Average score: 87.6
Distance (0,0) to (3,4): 5
Investment after 5 years: $1276.28