# Distance Calculation using Latitude & Longitude

In many cases, we need to calculate the distance between two points (given the latitude/longitude of those points) in PHP. It is being used to calculate distance between two points lat1, long1 and lat2, long2 and uses radius of earth in kilometers or miles as an argurments.

<?php

function distance(\$lat1, \$lon1, \$lat2, \$lon2, \$unit) {
\$theta = \$lon1 - \$lon2;
\$dist = acos(\$dist);
\$miles = \$dist * 60 * 1.1515;
\$unit = strtoupper(\$unit);

if (\$unit == "K") {
return (\$miles * 1.609344);
} else if (\$unit == "N") {
return (\$miles * 0.8684);
} else {
return \$miles;
}
}

echo distance(32.9697, -96.80322, 29.46786, -98.53506, "m") . " miles
";
echo distance(32.9697, -96.80322, 29.46786, -98.53506, "k") . " kilometers
";
echo distance(32.9697, -96.80322, 29.46786, -98.53506, "n") . " nautical miles
";

?>

The output of the code above could be something like this:

262.67779380543 miles
422.73893139401 kilometers
228.10939614064 nautical miles