PHP Math Functions
Introduction to PHP Math Functions
PHP provides a comprehensive set of mathematical functions for performing various calculations including basic arithmetic, trigonometry, logarithms, and statistical operations.
Basic Mathematical Operations
Arithmetic Functions
<?php
// Basic arithmetic
echo abs(-15); // 15 (absolute value)
echo ceil(4.3); // 5 (round up to nearest integer)
echo floor(4.7); // 4 (round down to nearest integer)
echo round(4.6); // 5 (round to nearest integer)
echo round(4.567, 2); // 4.57 (round to 2 decimal places)
// Min and Max
echo min(2, 3, 1, 6, 7); // 1
echo max(2, 3, 1, 6, 7); // 7
echo min([2, 3, 1, 6, 7]); // 1 (array syntax)
// Power and roots
echo pow(2, 3); // 8 (2^3)
echo sqrt(16); // 4 (square root)
echo exp(1); // 2.718... (e^1)
?>
Number Formatting
<?php
// Number formatting
echo number_format(1234.567); // 1,235
echo number_format(1234.567, 2); // 1,234.57
echo number_format(1234.567, 2, '.', ','); // 1,234.57
echo number_format(1234567.89, 2, ',', ' '); // 1 234 567,89
// Convert between number bases
echo decbin(10); // 1010 (decimal to binary)
echo bindec('1010'); // 10 (binary to decimal)
echo dechex(255); // ff (decimal to hexadecimal)
echo hexdec('ff'); // 255 (hexadecimal to decimal)
echo decoct(8); // 10 (decimal to octal)
echo octdec('10'); // 8 (octal to decimal)
// Base conversion
echo base_convert('10', 10, 2); // 1010 (decimal to binary)
echo base_convert('ff', 16, 10); // 255 (hex to decimal)
?>
Trigonometric Functions
<?php
// Basic trigonometric functions (angles in radians)
$angle = pi() / 4; // 45 degrees in radians
echo sin($angle); // 0.707... (sine)
echo cos($angle); // 0.707... (cosine)
echo tan($angle); // 1 (tangent)
// Inverse trigonometric functions
echo asin(0.5); // 0.524... (arcsine)
echo acos(0.5); // 1.047... (arccosine)
echo atan(1); // 0.785... (arctangent)
echo atan2(1, 1); // 0.785... (atan(y/x))
// Hyperbolic functions
echo sinh(1); // 1.175... (hyperbolic sine)
echo cosh(1); // 1.543... (hyperbolic cosine)
echo tanh(1); // 0.762... (hyperbolic tangent)
// Convert between degrees and radians
function degreesToRadians($degrees) {
return deg2rad($degrees);
}
function radiansToDegrees($radians) {
return rad2deg($radians);
}
echo deg2rad(180); // 3.14159... (π)
echo rad2deg(pi()); // 180
?>
Logarithmic Functions
<?php
// Natural logarithm (base e)
echo log(2.718281828); // 1 (ln(e) = 1)
// Logarithm with specified base
echo log(100, 10); // 2 (log₁₀(100) = 2)
echo log(8, 2); // 3 (log₂(8) = 3)
// Common logarithm (base 10)
echo log10(100); // 2
echo log10(1000); // 3
// Logarithm of (1 + x) - more accurate for small values
echo log1p(0.1); // 0.095... (ln(1.1))
// Exponential functions
echo exp(1); // 2.718... (e^1)
echo expm1(0.1); // 0.105... (e^0.1 - 1)
?>
Random Number Generation
<?php
// Basic random numbers
echo rand(); // Random integer
echo rand(1, 100); // Random integer between 1 and 100
// Better random number generator
echo mt_rand(); // Mersenne Twister random integer
echo mt_rand(1, 100); // MT random integer between 1 and 100
// Get maximum possible random value
echo mt_getrandmax(); // Maximum MT random value
// Seed the random number generator
mt_srand(12345); // Seed with specific value
mt_srand(); // Seed with current time (automatic)
// Random float between 0 and 1
function randomFloat($min = 0, $max = 1) {
return $min + mt_rand() / mt_getrandmax() * ($max - $min);
}
echo randomFloat(0, 10); // Random float between 0 and 10
// Cryptographically secure random numbers (PHP 7+)
echo random_int(1, 100); // Crypto-secure random integer
echo bin2hex(random_bytes(16)); // 32-character random hex string
?>
Advanced Mathematical Functions
Factorial and Combinations
<?php
// Factorial function
function factorial($n) {
if ($n <= 1) return 1;
return $n * factorial($n - 1);
}
// Iterative factorial (more efficient)
function factorialIterative($n) {
$result = 1;
for ($i = 2; $i <= $n; $i++) {
$result *= $i;
}
return $result;
}
// Combination (nCr)
function combination($n, $r) {
if ($r > $n) return 0;
return factorial($n) / (factorial($r) * factorial($n - $r));
}
// Permutation (nPr)
function permutation($n, $r) {
if ($r > $n) return 0;
return factorial($n) / factorial($n - $r);
}
echo factorial(5); // 120
echo combination(5, 2); // 10
echo permutation(5, 2); // 20
?>
Statistical Functions
<?php
// Statistical calculations
function mean(array $numbers) {
return array_sum($numbers) / count($numbers);
}
function median(array $numbers) {
sort($numbers);
$count = count($numbers);
$middle = floor($count / 2);
if ($count % 2 == 0) {
return ($numbers[$middle - 1] + $numbers[$middle]) / 2;
} else {
return $numbers[$middle];
}
}
function mode(array $numbers) {
$frequency = array_count_values($numbers);
$maxFreq = max($frequency);
return array_keys($frequency, $maxFreq);
}
function standardDeviation(array $numbers) {
$mean = mean($numbers);
$sumSquaredDiffs = 0;
foreach ($numbers as $number) {
$sumSquaredDiffs += pow($number - $mean, 2);
}
return sqrt($sumSquaredDiffs / count($numbers));
}
function variance(array $numbers) {
return pow(standardDeviation($numbers), 2);
}
$data = [1, 2, 3, 4, 5, 5, 6, 7, 8, 9];
echo "Mean: " . mean($data) . "\n"; // 5
echo "Median: " . median($data) . "\n"; // 5
echo "Mode: " . implode(', ', mode($data)) . "\n"; // 5
echo "Std Dev: " . standardDeviation($data) . "\n"; // 2.58...
echo "Variance: " . variance($data) . "\n"; // 6.67...
?>
Number Theory Functions
<?php
// Greatest Common Divisor
function gcd($a, $b) {
while ($b != 0) {
$temp = $b;
$b = $a % $b;
$a = $temp;
}
return $a;
}
// Least Common Multiple
function lcm($a, $b) {
return ($a * $b) / gcd($a, $b);
}
// Check if number is prime
function isPrime($n) {
if ($n < 2) return false;
if ($n == 2) return true;
if ($n % 2 == 0) return false;
for ($i = 3; $i <= sqrt($n); $i += 2) {
if ($n % $i == 0) return false;
}
return true;
}
// Generate Fibonacci sequence
function fibonacci($n) {
if ($n <= 0) return [];
if ($n == 1) return [0];
if ($n == 2) return [0, 1];
$fib = [0, 1];
for ($i = 2; $i < $n; $i++) {
$fib[$i] = $fib[$i-1] + $fib[$i-2];
}
return $fib;
}
echo "GCD(12, 18): " . gcd(12, 18) . "\n"; // 6
echo "LCM(12, 18): " . lcm(12, 18) . "\n"; // 36
echo "Is 17 prime? " . (isPrime(17) ? 'Yes' : 'No') . "\n"; // Yes
echo "First 10 Fibonacci: " . implode(', ', fibonacci(10)) . "\n";
?>
Constants and Special Values
<?php
// Mathematical constants
echo M_PI; // 3.14159265358979323846
echo M_E; // 2.7182818284590452354
echo M_LOG2E; // 1.4426950408889634074 (log₂(e))
echo M_LOG10E; // 0.43429448190325182765 (log₁₀(e))
echo M_LN2; // 0.69314718055994530942 (ln(2))
echo M_LN10; // 2.30258509299404568402 (ln(10))
echo M_PI_2; // 1.5707963267948966192 (π/2)
echo M_PI_4; // 0.78539816339744830961 (π/4)
echo M_1_PI; // 0.31830988618379067154 (1/π)
echo M_2_PI; // 0.63661977236758134308 (2/π)
echo M_SQRTPI; // 1.7724538509055160273 (√π)
echo M_2_SQRTPI; // 1.1283791670955125739 (2/√π)
echo M_SQRT2; // 1.4142135623730950488 (√2)
echo M_SQRT3; // 1.7320508075688772935 (√3)
echo M_SQRT1_2; // 0.70710678118654752440 (1/√2)
echo M_LNPI; // 1.1447298858494001741 (ln(π))
echo M_EULER; // 0.57721566490153286061 (Euler's constant)
// Check for special values
echo is_nan(sqrt(-1)) ? 'NaN' : 'Not NaN'; // NaN
echo is_infinite(log(0)) ? 'Infinite' : 'Finite'; // Infinite
echo is_finite(5.5) ? 'Finite' : 'Not Finite'; // Finite
?>
Practical Mathematical Applications
Financial Calculations
<?php
// Compound interest calculation
function compoundInterest($principal, $rate, $time, $compound = 1) {
return $principal * pow(1 + $rate / $compound, $compound * $time);
}
// Simple interest calculation
function simpleInterest($principal, $rate, $time) {
return $principal * (1 + $rate * $time);
}
// Loan payment calculation
function loanPayment($principal, $rate, $periods) {
if ($rate == 0) return $principal / $periods;
$monthlyRate = $rate / 12;
return $principal * ($monthlyRate * pow(1 + $monthlyRate, $periods)) /
(pow(1 + $monthlyRate, $periods) - 1);
}
$principal = 10000;
$rate = 0.05; // 5%
$time = 5; // years
echo "Compound Interest: $" . number_format(compoundInterest($principal, $rate, $time), 2) . "\n";
echo "Simple Interest: $" . number_format(simpleInterest($principal, $rate, $time), 2) . "\n";
echo "Monthly Payment: $" . number_format(loanPayment(200000, 0.04, 360), 2) . "\n";
?>
Geometric Calculations
<?php
// Area calculations
function circleArea($radius) {
return M_PI * pow($radius, 2);
}
function rectangleArea($length, $width) {
return $length * $width;
}
function triangleArea($base, $height) {
return 0.5 * $base * $height;
}
// Distance calculations
function distanceBetweenPoints($x1, $y1, $x2, $y2) {
return sqrt(pow($x2 - $x1, 2) + pow($y2 - $y1, 2));
}
// Angle calculations
function angleBetweenVectors($x1, $y1, $x2, $y2) {
$dot = $x1 * $x2 + $y1 * $y2;
$mag1 = sqrt($x1 * $x1 + $y1 * $y1);
$mag2 = sqrt($x2 * $x2 + $y2 * $y2);
return acos($dot / ($mag1 * $mag2));
}
echo "Circle area (r=5): " . number_format(circleArea(5), 2) . "\n";
echo "Distance: " . number_format(distanceBetweenPoints(0, 0, 3, 4), 2) . "\n";
?>
Data Analysis
<?php
// Linear regression
function linearRegression(array $x, array $y) {
$n = count($x);
$sumX = array_sum($x);
$sumY = array_sum($y);
$sumXY = 0;
$sumXX = 0;
for ($i = 0; $i < $n; $i++) {
$sumXY += $x[$i] * $y[$i];
$sumXX += $x[$i] * $x[$i];
}
$slope = ($n * $sumXY - $sumX * $sumY) / ($n * $sumXX - $sumX * $sumX);
$intercept = ($sumY - $slope * $sumX) / $n;
return ['slope' => $slope, 'intercept' => $intercept];
}
// Correlation coefficient
function correlation(array $x, array $y) {
$meanX = mean($x);
$meanY = mean($y);
$numerator = 0;
$sumXX = 0;
$sumYY = 0;
for ($i = 0; $i < count($x); $i++) {
$numerator += ($x[$i] - $meanX) * ($y[$i] - $meanY);
$sumXX += pow($x[$i] - $meanX, 2);
$sumYY += pow($y[$i] - $meanY, 2);
}
return $numerator / sqrt($sumXX * $sumYY);
}
$x = [1, 2, 3, 4, 5];
$y = [2, 4, 6, 8, 10];
$regression = linearRegression($x, $y);
echo "Slope: " . $regression['slope'] . "\n"; // 2
echo "Intercept: " . $regression['intercept'] . "\n"; // 0
echo "Correlation: " . correlation($x, $y) . "\n"; // 1
?>
PHP's mathematical functions provide powerful tools for performing complex calculations, statistical analysis, and mathematical modeling in your applications.