### Calculate the Distance Between Two Coordinates in PHP

Sometimes you search the web for some obscure problem you need to solve, like calculating the distance between two points, thinking that you’ll for sure never need this ever again. This, my friends, is not one of those examples. While I thought I’d never need this I have come back to this helpful function time and time again. Below is a helpful function that takes in two coordinates and returns the distance. Let’s break this down.

``````private function distanceGeoPoints(\$lat1, \$long1, \$lat2, \$long2) {

\$a = sin(\$dLat/2) * sin(\$dLat/2) +
sin(\$dLng/2) * sin(\$dLng/2);

\$c = 2 * atan2(sqrt(\$a), sqrt(1-\$a));
I won’t get into the somewhat complicated math that happens next but basically we’re taking the various conversions and coordinates we already have and performing geometric arithmetic to them in the form of sine and cosine and doing some other additions and multiplications and such. From this we come up with `\$a`.
Next we do some more geometric arithmetic in the form of an arc tangent and some square roots involving `\$a` which gives us `\$c`. Then all we have to do is multiply `\$c` with the `EARTH_RADIUS` constant we defined before to get our distance.