How can PHP be optimized to efficiently handle large datasets when performing proximity searches based on geographic coordinates?

When handling large datasets for proximity searches based on geographic coordinates in PHP, it is important to optimize the code for efficiency. One way to do this is by utilizing spatial indexes in a database to quickly retrieve nearby locations. Additionally, using algorithms like the Haversine formula to calculate distances between coordinates can help improve performance.

// Example of using spatial indexes in MySQL database for proximity search
$query = "SELECT id, name, lat, lng, ( 3959 * acos( cos( radians($lat) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians($lng) ) + sin( radians($lat) ) * sin( radians( lat ) ) ) ) AS distance FROM locations HAVING distance < $radius ORDER BY distance";
$result = mysqli_query($connection, $query);

while($row = mysqli_fetch_assoc($result)) {
    // Process the nearby locations
    echo $row['name'] . " is located at " . $row['distance'] . " miles away.";
}