# Sorting Proximity Search by Post Code by Distance (php / mysql)

I have a table (user_zip_codes) with the users' zip_code, latitude and longitude. I have found a function here on stackoverflow that finds zip codes within a specific radius:

``````function zipcodeRadius(\$lat, \$lon, \$radius) {
global \$mysqli;
\$zipcodeList = array();
\$sql = "SELECT userID,city,zip_code,country FROM user_zip_codes  WHERE (3958*3.1415926*sqrt((lat-\$lat)*(lat-\$lat) + cos(lat/57.29578)*cos(\$lat/57.29578)*(lon-\$lon)*(lon-\$lon))/180) <= \$radius GROUP BY zip_code";
if(\$stmt = \$mysqli->prepare(\$sql)) {
\$stmt->execute();
\$stmt->bind_result(\$userID,\$city,\$zip_code,\$country);
while(\$stmt->fetch()) {
\$zipcodeList[] = array('userID'=>\$userID,'city'=>\$city,'zip_code'=>\$zip_code,'country'=>\$country);
}
}
return \$zipcodeList;
}
```
```

It works perfectly. However, I would like the function to sort the array by distance (either by ASC og DESC). How should I adjust my query in order for this to happen?

UPDATE: The word 'distance' might appear ambiguous (thanks to Jorge). I simply wish to sort the zip_codes by distance meant as the distance between two points.

You could use something like

``````\$iDistance = 20;
\$fLat = x.y; // Your position latitude
\$fLon = x.y; // Your position longitude

\$strQuery = "
SELECT
*,
\$iRadius * 2 * ASIN(SQRT(POWER(SIN(( \$fLat - abs(pos.lat)) * pi() / 180 / 2),2) +
COS( \$fLat * pi()/180) * COS(abs(pos.lat) * pi() / 180) * POWER(SIN(( \$fLon - pos.lon) *
pi() / 180 / 2), 2) )) AS distance
FROM user_zip_codes pos
HAVING distance < \$iDistance
ORDER BY distance";
```
```

where you have to fetch your lat/lon value before using the SQL. This works for me