Math Functions

Common Math Functions and Trigonometry

The math library wraps C's: abs(), max(), min(), sqrt(), pow() or **, exp(), log($x, $base), log10(), fmod() and hypot(), plus sin(), cos(), tan(), their inverses and hyperbolic forms, all in radians (convert with deg2rad() and rad2deg()). atan2($y, $x) finds the correct quadrant. Constants include M_PI, M_E and M_SQRT2.

Haversine distance and the everyday math functions (math.php)PHP
<?php
declare(strict_types=1);
function distanceKm(float $lat1, float $lon1, float $lat2, float $lon2): float
{
    [$p1, $p2, $dl] = [deg2rad($lat1), deg2rad($lat2), deg2rad($lon2 - $lon1)];
    $a = sin(($p2 - $p1) / 2) ** 2 + cos($p1) * cos($p2) * sin($dl / 2) ** 2;
    return 6371.0088 * 2 * atan2(sqrt($a), sqrt(1 - $a));   // mean Earth radius in km
}
printf("London-New York %.1f km, atan2(1,1) = %.1f deg, hypot(3,4) = %s\n",
    distanceKm(51.5074, -0.1278, 40.7128, -74.0060), rad2deg(atan2(1, 1)), hypot(3, 4));
$prices = [19.99, 5, 42.5, 7.25];
echo max($prices), ' ', array_sum($prices) / count($prices), ' ', max(1, '10', 9.5), ' ',
    sqrt(2), ' ', fpow(0, -1), ' ', log(8, 2), ' ', exp(1), ' ', fmod(10, 3), ' ',
    log1p(1e-15), ' vs ', log(1 + 1e-15), "\n";
Output
London-New York 5570.2 km, atan2(1,1) = 45.0 deg, hypot(3,4) = 5
42.5 18.685 10 1.4142135623731 INF 3 2.718281828459 1 1.0E-15 vs 1.1102230246252E-15

max() follows PHP 8 comparison rules (Type Juggling) and returns the original value, here the string '10'. fpow() (PHP 8.4) is the IEEE 754 power function: 0 ** -1 is deprecated since 8.4, and fpow(0, -1) returns INF by design. log1p() and expm1() stay accurate near zero, where log(1 + $x) has already lost the digits. Totals over table rows belong in MySQL 524 's SUM() (MySQL).