Skip to content

Instantly share code, notes, and snippets.

@yetimdasturchi
Created February 13, 2024 05:31
Show Gist options
  • Save yetimdasturchi/d0ef3b33a7d431aeb3f925b61957b88e to your computer and use it in GitHub Desktop.
Save yetimdasturchi/d0ef3b33a7d431aeb3f925b61957b88e to your computer and use it in GitHub Desktop.
Find key from array with levenshtein distance
<?php
function findArrayWithLevenshtein( $input, $dic ) {
$minDistance = PHP_INT_MAX;
$correctedWord = $input;
foreach ( $dic as $key => $value ) {
$distance = levenshtein( $input, $key );
if ( $distance < $minDistance ) {
$minDistance = $distance;
$correctedWord = $key;
}
}
return $correctedWord;
}
$arr = [
'first' => 'Bir',
'two' => 'Ikki',
'three' => 'Uch',
'four' => 'To‘rt',
];
$key = findArrayWithLevenshtein( 'farst', $arr );
echo $arr[ $key ] . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment