hypot()
Today, we will discuss the hypot() function in PHP. This function is used to calculate the hypotenuse of a right-angled triangle.
The hypot() function in PHP returns the length of the hypotenuse of a right-angled triangle — equivalently, the straight-line (Euclidean) distance from the origin (0, 0) to the point (x, y). This page covers its syntax, why you would use it instead of a manual formula, and the gotchas to watch for.
Syntax
hypot(float $x, float $y): float$x— length of one side (or the x-coordinate of a point).$y— length of the other side (or the y-coordinate of a point).- Return value — a
float:sqrt($x * $x + $y * $y).
Both arguments are required, and the function always returns a float, even when the result is a whole number (hypot(3, 4) returns 5.0, which echo prints as 5).
What hypot() Computes
By the Pythagorean theorem, the hypotenuse of a right-angled triangle is the square root of the sum of the squares of the other two sides:
hypotenuse = √(side1² + side2²)
hypot() evaluates exactly this expression. The classic 3-4-5 triangle returns 5:
Here we store the two side lengths in variables, pass them to hypot(), and print the result. The function returns the floating-point value 5.
Why Not Just Use sqrt()?
You could write sqrt($x * $x + $y * $y) by hand, so why use hypot()? Two reasons:
- Readability — the intent ("compute a hypotenuse / distance") is obvious at a glance.
- Numerical safety —
hypot()is implemented to avoid overflow and underflow that a naivesqrt()of squared values can hit when$xor$yis very large or very small. Squaring a large number can exceed the float range and produceINF, whereashypot()is built to stay within range.
For everyday math the two approaches agree; for extreme magnitudes hypot() is the safer choice. See sqrt() and pow() for the lower-level building blocks.
Distance Between Two Points
Because hypot() returns the distance from (0, 0) to (x, y), you can find the distance between any two points by subtracting their coordinates first:
The differences are 3 and 4, so the distance is 5. This is the most common real-world use: measuring gaps in 2D space (UI layouts, game physics, geo math on a flat plane).
Notes and Gotchas
- Negative inputs are fine. Only the magnitudes matter, so
hypot(-3, -4)is also5— the squares cancel the signs. - The result is a float.
hypot(1, 1)returns1.4142135623731(PHP prints to its default precision of 14 significant digits). Don't compare ahypot()result to an integer with===. - Both arguments are mandatory.
hypot()takes exactly two numbers; for 3D distances, nest it:hypot(hypot($x, $y), $z).
Conclusion
hypot() gives you a concise, overflow-safe way to compute a hypotenuse or a 2D Euclidean distance without writing the Pythagorean formula by hand. Reach for it whenever you need the distance from the origin to a point, or — by subtracting coordinates — between any two points. For related math helpers, explore the full PHP Math Functions reference, abs(), and atan2().