Open In App

Calculate the Distance Between Two Points in PHP

Calculating the distance between two points is a common task in various applications, including mapping, location-based services, and geometry. In PHP, we can use different approaches to calculate this distance, depending on the coordinate system and the level of accuracy required.

Calculate the Distance Between Two Points (Euclidean Distance - Cartesian Coordinates)

We will use the distance formula derived from the Pythagorean theorem. The formula for distance between two point (x1, y1) and (x2, y2) is sqrt((x2 - x1)2 + (y2 - y1)2).

The Euclidean distance between two points in a Cartesian coordinate system can be calculated using the Pythagorean theorem.

<?php

function pointsDistance($x1, $y1, $x2, $y2) {
    $distance = sqrt(pow($x2 - $x1, 2) + pow($y2 - $y1, 2));
    return $distance;
}

// Driver code
$x1 = 3; $x2 = 7;
$y1 = 4; $y2 = 1;

echo "The distance between the points is: " 
    . pointsDistance($x1, $y1, $x2, $y2);

?>

Output
The distance between the points is: 5

Explanation:

Article Tags :