0

I have a input phone number 489998723(filled by user). And form database I get following prefixes with rate in array

4899981
4899
4899988
489998
4899987
48999

How I will perform the exact match. Example User entered 489998723 than it should match by 4899987.

Thanks in advance.

6
  • 5
    Possible duplicate of check multiple values exists php array Commented Aug 17, 2017 at 8:52
  • use array_search ( mixed $needle , array $haystack [, bool $strict = false ] ) Commented Aug 17, 2017 at 8:52
  • Why would you want a loose match on a phone number? Commented Aug 17, 2017 at 8:56
  • 1
    Hi, because according to these prefixes rate will be change for 489998 calling rate will be.023 and 4899987 calling rate will be .58 Commented Aug 17, 2017 at 9:16
  • So... you've definitely declared an array with these numbers as keys and rates as values, right? I didn't see it in the question details. Commented Aug 17, 2017 at 9:30

1 Answer 1

0

Suggest to use str_pos:

$phone = 489998723;

$arr = [
    4899981,
    4899,
    4899988,
    489998,
    4899987,
    48999,
];


rsort($arr);

$result = false;
foreach ($arr as $value) {
    // First match will be string of max length because of sorting
    if (strpos(strval($phone), strval($value)) === 0) {
        $result = $value;
        break;
    }
}

if ($result) {
    print_r ('result: ' . $result . PHP_EOL);
} else {
    print_r ('not found' . PHP_EOL);
}

Sandbox code

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks A.Mikhailov It works perfectly. Thank You very much

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.