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



Reffered: https://www.geeksforgeeks.org


PHP

Related
How to Find Average from Array in PHP? How to Find Average from Array in PHP?
PHP Program for XOR of Two Binary Strings PHP Program for XOR of Two Binary Strings
How to Create an Array of Given Size in PHP? How to Create an Array of Given Size in PHP?
PHP Program to Add Two Numbers PHP Program to Add Two Numbers
PHP Find Union &amp; Intersection of Two Unsorted Arrays PHP Find Union &amp; Intersection of Two Unsorted Arrays

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14