3v4l.org

run code in 300+ PHP versions simultaneously
<?php // input misspelled word $input = 'carrrot'; // array of words to check against $words = array('apple','pineapple','banana','orange', 'radish','carrot','pea','bean','potato'); // no shortest distance found, yet $shortest = -1; // 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); // check for an exact match if ($lev == 0) { // closest word is this one (exact match) $closest = $word; $shortest = 0; // break out of the loop; we've found an exact match break; } // if this distance is less than the next found shortest // distance, OR if a next shortest word has not yet been found if ($lev <= $shortest || $shortest < 0) { // set the closest match, and shortest distance $closest = $word; $shortest = $lev; } } echo "Input word: $input\n"; if ($shortest == 0) { echo "Exact match found: $closest\n"; } else { echo $lev."\n"; echo "Did you mean: $closest?\n"; }
Output for 4.3.0 - 4.3.11, 4.4.0 - 4.4.9, 5.0.0 - 5.0.5, 5.1.0 - 5.1.6, 5.2.0 - 5.2.17, 5.3.0 - 5.3.29, 5.4.0 - 5.4.45, 5.5.24 - 5.5.35, 5.6.7 - 5.6.28, 7.0.0 - 7.0.20, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.27, 8.2.0 - 8.2.17, 8.3.0 - 8.3.4
Input word: carrrot 6 Did you mean: carrot?

preferences:
265.72 ms | 405 KiB | 337 Q