Skip to content

Instantly share code, notes, and snippets.

@oRastor
Last active January 18, 2021 17:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oRastor/e1490fcfd4e66508001e to your computer and use it in GitHub Desktop.
Save oRastor/e1490fcfd4e66508001e to your computer and use it in GitHub Desktop.
Simple and fast php function to compare two phone numbers
<?php
function isEqualPhoneNumber($phoneA, $phoneB, $substringMinLength = 7)
{
if ($phoneA == $phoneB) {
return true;
}
// remove "0", "+" from the beginning of the numbers
if ($phoneA[0] == '0' || $phoneB[0] == '0' ||
$phoneA[0] == '+' || $phoneB[0] == '+') {
return isEqualPhoneNumber(ltrim($phoneA, '0+'), ltrim($phoneB, '0+'));
}
// change numbers if second is longer
if (strlen($phoneA) < strlen($phoneB)) {
return isEqualPhoneNumber($phoneB, $phoneA);
}
if (strlen($phoneB) < $substringMinLength) {
return false;
}
// is second number a first number ending
$position = strrpos($phoneA, $phoneB);
if ($position !== false && ($position + strlen($phoneB) === strlen($phoneA))) {
return true;
}
return false;
}
// tests
$tests = array(
array('+380441234567', '+380441234567', true),
array('*111#', '*111#', true),
array('923001122333', '03001122333', true),
array('+380951000000', '380951000000', true),
array('0951000000', '0961000000', false),
array('0951033333', '33333', false),
array('+380951002030', '00380951002030', true),
array('0951002030', '095100203', false),
array('011380951002030', '+380951002030', true)
);
$passed = 0;
foreach ($tests as $testRecord) {
echo $testRecord[0] . ' AND ' . $testRecord[1] . PHP_EOL;
$result = isEqualPhoneNumber($testRecord[0], $testRecord[1]);
if ($result) {
echo 'Equal' . PHP_EOL;
} else {
echo 'Not Equal' . PHP_EOL;
}
if ($result == $testRecord[2]) {
$passed++;
echo '+++' . PHP_EOL;
} else {
echo '---' . PHP_EOL;
}
echo PHP_EOL;
}
echo $passed . ' of ' . count($tests) . ' Passed' . PHP_EOL;
@oRastor
Copy link
Author

oRastor commented Sep 18, 2015

Test result output:

+380441234567 AND +380441234567
Equal
+++

*111# AND *111#
Equal
+++

923001122333 AND 03001122333
Equal
+++

+380951000000 AND 380951000000
Equal
+++

0951000000 AND 0961000000
Not Equal
+++

0951033333 AND 33333
Not Equal
+++

+380951002030 AND 00380951002030
Equal
+++

0951002030 AND 095100203
Not Equal
+++

011380951002030 AND +380951002030
Equal
+++

9 of 9 Passed

@alyjee
Copy link

alyjee commented May 4, 2018

Hi,
I liked it, and it worked for my use case.
Nice and simple to begin with.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment