I have 3 different areas, MyArea1, MyArea2, MyArea3. Each of these have an array of postcodes:
$myArea1=array("AB1","AC2","AD1");
$myArea2=array("BC1","BC2","BC3");
$myArea3=array("CD1","CD2","CD3");
The postcodes I need to check would be like the following "BC2 4YZ".
The following won't work as it checks for a complete match:
if (in_array($row['postcode'], $myArea1)) { $Area = 'Area 1'; }
else if (in_array($row['postcode'], $myArea2)) { $Area = 'Area 2'; }
else if (in_array($row['postcode'], $myArea3)) { $Area = 'Area 3'; }
else { $Area = 'No Match'; }
I've got the following that works:
foreach ($myArea1 as $myArea1pc) {
if (strpos($row['postcode'],$myArea1pc) !== false) {
$Area = 'Area 1';
}
}
However is there a way of looping this for all of my arrays?
Edit: There may sometimes be postcodes such as "BC24" in my arrays.
I would try to use in_array
for this.
$input = $row['postcode'];
$areas = array(
'Area 1' => array("AB1","AC2","AD1"),
'Area 2' => array("BC1","BC2","BC3"),
'Area 3' => array("CD1","CD2","CD3"),
);
// Take out the first 3 letter:
$part = substr(trim(str_replace(' ', '', $input)), 0, -3);
$Area = 'No match';
// Find which "area" array contains it
foreach ($areas as $k => $v) {
if (in_array($part, $v)) {
$Area = $k;
break;
}
}