function findNearestStations2($location) { global $markers; $debug = false; // the list of stations to return $stations = array(); $maxDist = 0; foreach ($markers as $marker) { $currentStation = new Station($marker, distance2Loc($location, $marker)); if (count($stations) == 3) { $maxDist = max($stations[0]->getDistance(), $stations[1]->getDistance(), $stations[2]->getDistance()); } if (count($stations) < 3) { $stations[] = $currentStation; if (count($stations) < 3) { continue; } } if ($maxDist > $currentStation->getDistance()) { //Find station with maxDist $i = 0; for (; $i < count($stations); $i++) { if ($stations[$i]->getDistance() == $maxDist) { break; } } //Replace station with maxDist with currentStation $stations[$i] = $currentStation; } } if ($debug) { echo "end stations:<br/>\n"; print_r($stations); echo "<br/>\n"; } // this array should be the three closest stations return $stations; }