Skip to content
Advertisement

Get closest city from array

I would like to create a function that returns the closest city (and the remaining distance to the city) from an array.

The numbers in the array represent the distance from the Starting point. $currentPosition is the current distance from the starting point.

E.g. at $currentPosition = 80, getCity() should return [60, ‘München’]. But at the moment, it returns [-80, null];

Unfortunately, it does not work as planned.

So this is my code:

$cities= [
  [ 70, "Ingolstadt" ],
  [ 140, "München" ],
  [ 234, "Innsbruck" ],
  [ 443, "Venedig" ],
  [ 622, "Florenz" ],
  [ 835, "Rom" ],
  [ 973, "Neapel" ],
];

function getCity( $currentPosition) {
  for ($i=0; ;) {
    if ( $currentPosition > $cities[$i][0]  && $currentPosition < $cities[$i+1][0] ) {
      $i++;
    }else {
      $distance = $cities[$i][0] - $currentPosition;
      $city= $cities[$i][1];
      return array( $distance , $city);
      break;
    }
  }
}

Advertisement

Answer

Try this one

<?php 

    $cities = [
      [ 70, "Ingolstadt" ],
      [ 140, "München" ],
      [ 234, "Innsbruck" ],
      [ 443, "Venedig" ],
      [ 622, "Florenz" ],
      [ 835, "Rom" ],
      [ 973, "Neapel" ],
    ];


    $diff = 2147483647;
    $pos = 0;

    function getCity($currentPosition) {

      global $cities;
      global $diff;
      global $pos;

      for ($i=0; $i<count($cities); $i++) {
        if($cities[$i][0] > $currentPosition) {
            if(($cities[$i][0] - $currentPosition) < $diff) {
                $diff = $cities[$i][0] - $currentPosition;
                $pos = $i;
            }
        }
      }
      return "Nearest city is " . $cities[$pos][1] . " and the left distance is " . $diff;
    }

?>


<!DOCTYPE html>
<html>
<body>

    <h1><?php echo getCity(80); ?></h1>

</body>
</html>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement