-2

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.

Naveed
  • 41,517
  • 32
  • 98
  • 131
user892970
  • 73
  • 1
  • 6
  • What exactly are you stuck with? – Pekka May 20 '12 at 17:22
  • I am stuck because, normally, searching the list for a match of "IV21" would return false, because in the list is only "IV1-28" - I want this to return true. I need somehow for the IV1-28 to be broken down (by code, not manually) into it's constituent parts, so that the input is checked against all the postcodes from IV1 thru IV28 - this then would be true. – user892970 May 20 '12 at 21:37

3 Answers3

1

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);
gunnx
  • 1,229
  • 7
  • 16
0

http://php.net/manual/en/function.explode.php (to split your list into only the left hand side), add the left hand side into an array, and use http://php.net/manual/en/function.in-array.php - should get you somewhere close to what you need

ChrisW
  • 4,970
  • 7
  • 55
  • 92
  • It's already split into the left hand side. I need it to programmatically translate (somehow) the IV1-28 into IV1,IV2,IV3,IV4,IV5,IV6,IV7,IV8,IV9,IV10,IV11,IV12,IV13,IV14,IV15,IV16,IV17,IV18,IV19,IV20,IV21,IV22,IV23,IV24,IV25,IV26,IV27,IV28 - then I can check the input against the list. – user892970 May 20 '12 at 21:43
  • Nothing I know of, I haven't had chance to try it yet. – user892970 May 21 '12 at 15:53
0

use strpos function. returns int if found or else false. note that matching IV1 would give true even of IV11 is found. so use the following script

$code="IV21";
$list="IV1-..........etc";
if(strpos($list,$code."-") || strpos($list,$code.",") { 
//true
}
else {
//false 
}

the "-" and "," is to ensure that the string ends so that IV11 won't give true if we search for IV1

Xpleria
  • 5,472
  • 5
  • 52
  • 66