phparraysstringsimilarity

PHP - How do I partially compare elements in 2 arrays


I have 2 arrays:

$arr1 = array('Test', 'Hello', 'World', 'Foo', 'Bar1', 'Bar'); and
$arr2 = array('hello', 'Else', 'World', 'Tes', 'foo', 'BaR1', 'Bar'); 

I need to compare the 2 arrays and save the position of the matching elements to a 3rd array $arr3 = (3, 0, 2, 4, 5, 6); //expected result, displaying position of matching element of $arr1 in $arr2.

By 'matching' I mean all elements that are identical (ex. World), or partially the same (ex. Test & Tes) and also those elements that are alike but are in different case (ex. Foo & foo, Bar & bar).

I've tried a series of combinations and of various functions without success, using functions like array_intersect(), substr_compare(), array_filter() and more. I'm not asking for the exact solution, just something to get me on the right track because i'm going around in circles all afternoon.


Solution

  • This seemed to work for me, but I'm sure there are some edge cases I'm missing that you'd need to test for:

    foreach( $arr1 as $i => $val1) {
        $result = null;
        // Search the second array for an exact match, if found
        if( ($found = array_search( $val1, $arr2, true)) !== false) {
                $result = $found; 
        } else {
            // Otherwise, see if we can find a case-insensitive matching string where  the element from $arr2 is at the 0th location in the one from $arr1
            foreach( $arr2 as $j => $val2) {            
                if( stripos( $val1, $val2) === 0) {
                    $result = $j;
                    break;
                }
            }
        }
        $arr3[$i] = $result;
    }
    

    It produces your desired output array:

    Array ( [0] => 3 [1] => 0 [2] => 2 [3] => 4 [4] => 5 [5] => 6 )