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:
- pointDistance Function: This function takes the coordinates of two points as arguments.
- sqrt and pow Functions: The sqrt function calculates the square root, and the pow function raises a number to a power. Together, they implement the Pythagorean theorem.
- $distance: This variable stores the calculated distance between the two points.
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.