# Which function is faster levenshtein() or similar_text()?

## Brief

I wrote two functions using levenshtein() and similar_text(). The functions will find similar words from the dictionary in the input array with the wrong words. At the same time, the found words are stored in the associative array by passing the wrong variant to the array key and the correct variant of the words to the value of the array.

## First function using levenshtein()

function getLevenshtein($inputWordsArray,$dict){
$shortest = -1;$result = array();
foreach ($inputWordsArray as$input) {
foreach ($dict as$word) {
$lev = levenshtein($input, $word); if ($lev == 0) {
$closest =$word;
$shortest = 0; break; } if ($lev <= $shortest ||$shortest < 0) {
$closest =$word;
$shortest =$lev;
$result[$input] = $closest; } } } if($count = count($result) > 0) return$result;
return false;
}


## Second function using similar_text()

function getSimilar($inputWordsArray,$dict){
$result = array(); foreach ($inputWordsArray as $input){$match = 0;
foreach ($dict as$word){
similar_text($word,$input, $percent); if ($percent > $match){$closest = $word;$match = $percent; } }$result[$input] =$closest;
}
if($count = count($result) > 0) return $result; return false; }  ## Usage: $inputWordsArray = array('desription','programing','exteds','plaer','moie','edt','laavel');
$dict = array('description','programming','extends','player','level','laravel','etc','edit','movie'); echo "Usage levenshtein:"; echo "<pre>"; print_r(getLevenshtein($inputWordsArray, $dict)); echo "</pre>"; echo "Usage similar text:"; echo "<pre>"; print_r(getSimilar($inputWordsArray, \$dict));
echo "</pre>";


### Output:

Usage levenshtein:

Array
(
[desription] => description
[programing] => programming
[exteds] => extends
[plaer] => player
[moie] => movie
[edt] => edit
[laavel] => laravel
)

Usage similar text:

Array
(
[desription] => description
[programing] => programming
[exteds] => extends
[plaer] => player
[moie] => movie
[edt] => edit
[laavel] => laravel
)


Is my algorithm correct? Is it possible to optimize the function? Which one should I use for a large number of vocabulary? I need the result in the form of an associative array.

• soo ... "which is faster" is a question you can answer yourself... Which one is it? Have you run them against the same input? – Vogel612 Nov 15 '17 at 17:50
• There are many optimization you could put in your code. Let me suggest one: Check if the input word occurs in the dictionary. Then you can skip checking the word against all the words in the dictionary. Many other optimizations are possible, of increasing complexity. What you're basically doing now is a brute force attack of the problem. – KIKO Software Nov 15 '17 at 21:13
• Please post your answer with examples if it possible @KIKO Software – Andreas Hunter Nov 16 '17 at 8:42