0

I have the following PHP code:-

<?php
if( have_rows('postcode_checker', 'option') ):
    while ( have_rows('postcode_checker', 'option') ) : the_row(); ?>
        <?php 
            $postcodes .= get_sub_field('postcodes');
            $postcode_url = get_sub_field('page');
        ?>
    <?php endwhile;
else : endif;

$postcode_array = $postcodes; // This collects postcodes, i.e. LE67, LE5 etc...
$postcode_array = explode(',', $postcode_array);
$postcode_array = str_replace(' ', '', $postcode_array);
$postcode_search = $_POST['postcode']; // This will be a single postcode i.e. LE67

if (in_array($postcode_search, $postcode_array)) {
echo 'yes';
} else {
echo 'no';
}
?>

So the code above is working fine if I want to look up say LE67 and it finds LE67 in the array and returns 'yes'. Now if I search LE675AN for example it will return no even though it needs to be returning yes as it is within the postcode area.

Any idea's on how I can achieve this?

nsilva
  • 5,184
  • 16
  • 66
  • 108
  • Do you tried with `substr()`? http://php.net/manual/en/function.substr.php – Ferrmolina Aug 13 '18 at 14:39
  • You need a clear definition of what a match should be. You say "i.e. LE67, LE5 etc...". That leads me to believe that "LE6" could also be in that list. Is that correct? If so, how do we know that LE675AN should match LE67 and not LE6? – Patrick Q Aug 13 '18 at 14:39
  • Possible duplicate of [Search for PHP array element containing string](https://stackoverflow.com/questions/12315536/search-for-php-array-element-containing-string) – No Name Aug 13 '18 at 14:40
  • php has strpos() function to do that. but be careful when using that. you have to use precedence operator. – Gabriel Aug 13 '18 at 14:41
  • in_array doesn't do substring matching, it matches indexes and values as a whole. LE67 does not equal LE675AN, and the code is working as it should. If you only want to compare the first part (postdistrict) of the postcode list, you need to be stripping that out of all the postcodes and putting the values into their own array. – John Bell Aug 13 '18 at 14:41
  • I want to compare just the first part, issue is that some postcodes are only 3 characters, others are 4? – nsilva Aug 13 '18 at 14:43
  • substr([postcode], 0, strpos([postcode],' ')); – John Bell Aug 13 '18 at 14:46

0 Answers0