Open In App

Calculate the Distance Between Two Points in PHP

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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
<?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.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads