phparraysmultidimensional-arrayphone-numbersanitization

Find value in a column of a 2d array when non-digital characters may interfere


I have an array that contains phone numbers in different format:

$myArr = [
    ['122-33-2222'],
    ['(122) 433-5555'],
    ['122 644.8888']
];

I need to check if another number is in that array. I assume I need to loop through array and strip all non-numeric characters before I compare.

$findNumber = 122.433.5555;
$varPhone = preg_replace("/[^0-9,.]/", "", $findNumber);

foreach ($myArr AS $phone) {
    if (preg_replace("/[^0-9,.]/", "", $phone) == $varPhone) {
        echo "found";
    } else {
        echo "not found";
    }
}

I think I'm close but it's not quite there. What am I missing?


Solution

  • The phone number is in the key [0] of each first-level array element, so you can't compare each instance of $phone directly. Also, I would replace all non-digit characters so that different notations still turn out as the same number.

    <?php
    // initialize array for the sake of this demo, to make this snippet work
    $myArr = array(array(), array(), array());
    $myArr[0][0] = '122-33-2222';
    $myArr[1][0] = '(122) 433-5555';
    $myArr[2][0] = '122 644.8888';
    
    $findNumber = "122.433.5555";
    
    function cleanNumber($in) {
      return preg_replace("/[^0-9]/", "", $in);
    }
    
    foreach ($myArr AS $phone) {
       // the number is in the key [0] for each first-level array element
       if (cleanNumber($phone[0]) == cleanNumber($findNumber)) {
          echo "found<br>";
       } else {
          echo "not found<br>";
       }
    }
    

    this will output:

    not found
    found
    not found