Search code examples
phparrayssortinglevenshtein-distance

Sort array of values by their levenshtein distance from a comparison string


I have a form that compares 1 word with many and outputs a list of levenshtein scores. How can I get those scores so they list in order, smallest levenshtein score 1st:

$string5 = $_POST["singleword"];
$string6 = $_POST["manywords"];
$array6 = explode(', ',$string6); 

foreach ($array6 as $derp)
{
    echo $string5, "/", $derp, ": ", levenshtein($string5, $derp), "<br>";
}

The current list output would be like this:

apple/mango: 5
apple/peach: 5
apple/toothpaste: 8
apple/apes: 3

I want it to be like this:

apple/apes: 3
apple/mango: 5
apple/peach: 5
apple/toothpaste: 8

Solution

  • $string5 = $_POST["singleword"];
    $string6 = $_POST["manywords"];
    
    $words = array_flip(array_map('trim', explode(',', $string6)));
    
    foreach ($words as $key => $value)
    {
        $words[$key] = levenshtein($string5, $key);
    }
    
    asort($words);
    
    foreach ($words as $key => $value)
    {
        printf('%s / %s: %s<br />', $string5, $key, $value);
    }