Search code examples
phparrayslevenshtein-distance

Determine if any array value compared against a given string has a qualifying levenshtein score


I want to verify if a levenshtein of factor <= 2 is present in an array. So:

in_array("test", $some_array);

to something like "check if in array, can have errors if levenshtein factor <= 2, by comparison"

levenshtein("test", $element_of_array_by_'in_array'_function);

Is this possible or do I have to iterate the array?


Solution

  • This should work for you:

    You are looking for array_reduce(). With this you can reduce your array to one single return value.

    You start with FALSE as return value. Then you loop through each array element and check if the return value of levenshtein() is smaller or equals 2.

    If not then your return value of array_reduce() won't change and is still FALSE. If it is smaller or equals 2 you change the value to TRUE and array_reduce() will return TRUE.

    array_reduce($some_array, function($keep, $v){
        if(levenshtein($v, "test") <= 2)
            return $keep = TRUE;
        return $keep;
    }, FALSE);