I have the following code that is displaying the results of a simply foreach statement. What I want to do is order the results by $lev from lowest value to highest value. Any ideas?
// input misspelled word
$input = 'carrrot';
// array of words to check against
$words = array('apple','pineapple','banana','orange', 'radish','carrot','pea','bean','potato');
//loop through words to find the closest
foreach ($words as $word) {
// calculate the distance between the input word,
// and the current word
$lev = levenshtein($input, $word);
if($lev <= 10) {
echo $word."-".$lev."<br>";
}
}
The idea is that usort takes an array and passes pairs of elements to the function that you provide as the second argument. That function has to take the two values and compare them somehow, returning 0 if they are equivalent, -1 if the first element should come before the second, and 1 if it should come after. This happens until all the elements in the array have been sorted.
It would be nice to keep the levenstein rating. The ouput of the usort is not really outputting the way the rest of the script will need it. Is there another way to go about this?
which will give you a sorted array where the words are the keys, and the scores are the values. Running it on your example word list would give the following output: