How can PHP be used to calculate distances between postal codes for a radius search?

To calculate distances between postal codes for a radius search in PHP, you can use the Haversine formula. This formula takes into account the latitude and longitude of two points to calculate the distance between them. By converting postal codes to their respective coordinates (latitude and longitude), you can then use the Haversine formula to determine the distance between them.

function calculateDistance($lat1, $lon1, $lat2, $lon2) {
    $earthRadius = 6371; // in kilometers

    $dLat = deg2rad($lat2 - $lat1);
    $dLon = deg2rad($lon2 - $lon1);

    $a = sin($dLat / 2) * sin($dLat / 2) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dLon / 2) * sin($dLon / 2);
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));

    $distance = $earthRadius * $c;

    return $distance;
}

$postalCode1 = "10001";
$postalCode2 = "20001";

// Get latitude and longitude for postal codes
$lat1 = getLatitude($postalCode1);
$lon1 = getLongitude($postalCode1);
$lat2 = getLatitude($postalCode2);
$lon2 = getLongitude($postalCode2);

$distance = calculateDistance($lat1, $lon1, $lat2, $lon2);
echo "The distance between $postalCode1 and $postalCode2 is $distance kilometers.";