Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6914999
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T09:25:12+00:00 2026-05-27T09:25:12+00:00

In my php application I want to get the nearest postal code of the

  • 0

In my php application I want to get the nearest postal code of the given post code.
That means I enter a post code as 680721 I want to get the nearest post code of this from my database.

How can I do this?

This is the table I used for store postal codes.
enter image description here

enter image description here

Here varpin is the postal code field.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T09:25:13+00:00Added an answer on May 27, 2026 at 9:25 am

    Having said all this, a quick browse through the “External Links” on the UK Postcodes Wikipedia entry, and I quickly found an article by Paul Jenkins entitled UK Post Code Distance Calculation in PHP, which is fantastic, you can even download it here (uk_postcode_calc.zip).
    After a short examination it seems this does exactly what it says on the tin, and simply calculates the distance.
    However, with a quick google for php distance calculation, you can quickly find that there are more refined equivalents of the distance calculation. I thought it might be a good idea to use one of those instead.
    After a bit of tweaking, here’s what I came up with in the end:

    function distance($lat1, $lon1, $lat2, $lon2, $u=’1′) {
    $u=strtolower($u);
    if ($u == ‘k’) { $u=1.609344; } // kilometers
    elseif ($u == ‘n’) { $u=0.8684; } // nautical miles
    elseif ($u == ‘m’) { $u=1; } // statute miles (default)
    $d=sin(deg2rad($lat1))*sin(deg2rad($lat2))+cos(deg2rad($lat1))*cos(deg2rad($lat2))*cos(deg2rad($lon1-$lon2));
    $d=rad2deg(acos($d));
    $d=$d*60*1.1515;
    $d=($d*$u); // apply unit
    $d=round($d); // optional
    return $d;
    }
    

    So, that’s the hard parts done (database and maths), next is simply a case of using this information to “find the closest” from the postcode we input to an array of postcodes we supply…
    To find the “closest” postcode, effectively what we’re trying to do is find the “shortest” distance between the postcodes, or, simply the smallest number in the results, assuming we put the results into an array with the key as the postcode and the distance as the value.
    All we have to do is create a simple script that will find the smallest number in a given array, then return the appropriate key. Simple!

    function closest ($needle,$haystack) {
    if (!$needle || !$haystack) { return; }
    if (!is_array($haystack)) { return; }
    $smallest=min($haystack); //smallest value
    foreach ($haystack as $key => $val) {
    if ($val == $smallest) { return $key; }
    }
    }
    

    The above script does exactly what we want, using the “min” function we can quickly work out what we need to return.
    The only task left is to bind all this together, we need to create two functions that will:
    Get the distance using the postcode to get the longitude and latitude from the database.
    Create an array with the postcodes as the keys, and the distance as the values.
    Very simple!
    Function 1, Postcode Distance

    function postcode_distance ($from,$to) {
    // Settings for if you have a different database structure
    $table=’postcodes_uk’;
    $lat=’lat’;
    $lon=’lon’;
    $postcode=’postcode’;
    // This is a check to ensure we have a database connection
    if (!@mysql_query(‘SELECT 0′)) { return; }
    // Simple regex to grab the first part of the postcode
    preg_match(‘/[A-Z]{1,2}[0-9R][0-9A-Z]?/’,strtoupper($from),$match);
    $one=$match[0];
    preg_match(‘/[A-Z]{1,2}[0-9R][0-9A-Z]?/’,strtoupper($to),$match);
    $two=$match[0];
    $sql = “SELECT `$lat`, `$lon` FROM `$table` WHERE `$postcode`=’$one’”;
    $query = mysql_query($sql);
    $one = mysql_fetch_row($query);
    $sql = “SELECT `$lat`, `$lon` FROM `$table` WHERE `$postcode`=’$two’”;
    $query = mysql_query($sql);
    $two = mysql_fetch_row($query);
    $distance = distance($one[0], $one[1], $two[0], $two[1]);
    // For debug only…
    //echo “The distance between postcode: $from and postcode: $to is $distance miles\n”;
    return $distance;
    }
    Function 2, Postcode Closest
    function postcode_closest ($needle,$haystack) {
    if (!$needle || !$haystack) { return; }
    if (!is_array($haystack)) { return; }
    foreach ($haystack as $postcode) {
    $results[$postcode]=postcode_distance($needle,$postcode);
    }
    return closest($needle,$results);
    }
    

    So, with that done, place the 4 above functions into a file such as “postcode.php”, ready for use in the real world…
    Test case:

    <?php
    include_once(‘postcode.php’);
    if ($_POST) {
    include_once(‘db.php’);
    $postcodes=array(‘TF9 9BA’,'ST4 3NP’);
    $input=strtoupper($_POST['postcode']);
    $closest=postcode_closest($input,$postcodes);
    }
    if (isset($closest)) {
    echo “The closest postcode is: $closest”;
    }
    ?>
    <form action=”" method=”post”>
    Postcode: <input name=”postcode” maxlength=”9″ /><br />
    <input type=”submit” />
    </form>
    

    You can download this script here: postcode_search.phps
    Note: In the above test case, I have a “db.php” file which contains my database details and starts a database connection. I suggest you do the same.
    Ensure you have your database populated, you should be able to use Paul Jenkins’s UK Postcode csv, allowing you to use your own table structure.
    Well, that’s all folks, I can now use this script to provide any locations that match the “closest” postcode.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

We've got a PHP application and want to count all the lines of code
I just want to send SMS from my web application in PHP. Can anyone
I want my PHP Zend Application to get access to the database. Because the
Is there any better PHP CRUD code generator? I want to get Data Access
I have this query which I want to run in my PHP application back
I want to get some input from experienced PHP developers on how to structure
I am creating store locator application. This application should show nearest store to given
I'm creating a new PHP application and want to make sure I get the
i have this code: <script> $(document).ready(function() { refresh(); }); function refresh() { $.get('getMessageDetails.php', function
I am maintaining an OO PHP application that loads everything to $this array. When

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.