Search code examples
phpfunctionpostal-code

PHP check postcode is in list


I have a list of postcode areas (left hand part only) as below:

IV1-28,IV30-32,IV36,IV40-49,IV52-56,IV63,KW1-3,KW5-14,PA21-38,PH1-26,PH30-41,PH49-50,LD1-99,SY16-20,SY23-25

My input is a UK Postcode eg. IV21

I need a PHP function to check if the input postcode (eg IV21) is in the list.

This would be simple enough, but the list is in the form IV1-28 as opposed to being a 'normal' list such as IV1,IV2,IV3,IV4,IV5,IV6...IV26,IV27,IV28 etc.

Help is much appreciated. Thanks in advance.


Solution

  • loops through an array of codes and splits them into the number then checks if that number is within the range

    $list = array("IV1-28","AB1-10");
    $found = false;
    $input = "AB10";
    $inputCode = substr($input,0,2);
    $inputNumber = substr($input,2);
    foreach ($list as $l)
    {
        $lCode = substr($l,0,2);
        $lNumber = substr($l,2);
        $listNumbers = explode("-",$lNumber);
        if (($inputNumber >= $listNumbers[0]) && ($inputNumber <= $listNumbers[1]) && ($inputCode==$lCode))
        {
            $found = true;
            break;
            }           
    }
    
    var_dump($found);