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?

7
  • Do you tried with substr()? php.net/manual/en/function.substr.php Commented Aug 13, 2018 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? Commented Aug 13, 2018 at 14:39
  • Possible duplicate of Search for PHP array element containing string Commented Aug 13, 2018 at 14:40
  • php has strpos() function to do that. but be careful when using that. you have to use precedence operator. Commented Aug 13, 2018 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. Commented Aug 13, 2018 at 14:41

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.