Hypotenuse In Action¶
<?php
// distance between two 2D points
$x1 = 3; $y1 = 4;
$x2 = 7; $y2 = 1;
$dist = hypot($x2 - $x1, $y2 - $y1); // 5.0
// why not just sqrt(($dx)**2 + ($dy)**2)?
// because hypot() avoids intermediate overflow
// QUICK TIP STRAIGHT FROM GAME DEV: sometimes you only want to *compare* distances, and
// square root is SLOW
// in this case, just compare squared values, it's equivalent!
$dx1 = $x2 - $x1;
$dy1 = $y2 - $y1;
$dist1Sq = $dx1 * $dx1 + $dy1 * $dy1;
// some other points in space...
$dist2Sq = $dx2 * $dx2 + $dy2 * $dy2;
if ($dist1Sq < $dist2Sq) { // squared value compared, way faster without square root!
echo "Point 2 is closer to Point 1
";
} else {
echo "Point 3 is closer to Point 1
";
}
PHP has a built-in Euclidean distance function, if you need to calculate a distance!
Sounds complex, but it’s just the hypotenus! Without the overflow risk of doing it manually.
If you ONLY need to compare distances, don’t miss the tip at the end of the code snippet!
See Also¶
PHP Features¶
Last updated: 14 July 2026