Combining levenshtein with in_array in PHP?

I want to check if the levenshtein factor <= 2 is present in the array. So:

in_array("test", $some_array);

      

to something like "check if in an array, there might be errors if levenshtein coefficient <= 2, for comparison"

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

      

Is this possible, or do I need to iterate over the array?

+3


source to share


1 answer


This should work for you:

You are looking for array_reduce()

. That being said, you can reduce the array to a single return value.

You start with FALSE

as a return value. Then you loop through each element of the array and check if the return value is less than levenshtein()

or equal to 2.



If not, then your return value array_reduce()

will not change and will remain FALSE

. If it is less than or equal to 2, you change the value to TRUE

, and array_reduce()

returns TRUE

.

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

      

+3


source







All Articles