# How to sort by proximity using PHP?

## Question:

I have some locations registered in the database and each of them has the longitude and latitude. When the user enters the site, I ask him to enter his geolocation. I'm using the PHPGeo library to calculate the distance between each one, but how can I organize this result?

Ex: Location 1, Location 2, Location 3

I'm closest to Location 2 , then Location 3 , then Location 1 .

How do I organize this?

Starting from PHPGeo itself, as mentioned in the question:

## Vincenty's Formula

``````<?php
use Location\Coordinate;
use Location\Distance\Vincenty;
\$coordenada1 = new Coordinate( -23.575, -46.658 );
\$coordenada2 = new Coordinate( -21.279, -44.297 );
?>
``````

## Haversine's formula

Haversine's formula is much faster to calculate, but less accurate.

``````<?php
use Location\Coordinate;
use Location\Distance\Haversine;
\$coordenada1 = new Coordinate( -23.575, -46.658 );
\$coordenada2 = new Coordinate( -21.279, -44.297 );
?>
``````

GitHub – PHPGeo

## Calculating the distance from the origin to various points, and sorting:

To sort the results, you can start from the reference point, and in a loop store the calculated distances in an array, and then sort them:

``````<?php
\$origem       = new Coordinate( -22.155, -45.158 );

// Lembre-se de inicializar as arrays de acordo com seu código
\$nome = 'Ponto1';
\$coordenada = new Coordinate( -23.575, -46.658 );

\$nome = 'Ponto2';
\$coordenada = new Coordinate( -21.279, -44.297 );

\$nome = 'Ponto3';
\$coordenada = new Coordinate( -21.172, -44.017 );
... etc ...

// Vamos calcular a distância de todos para a \$origem: