Search code examples
phparrayslistlevenshtein-distance

How to compare 1 word versus many and output a list of levenshtein scores


I have a form where I can input two words then compare the levenshtein score, that works fine.

I want to be able to compare 1 word with a string of words delimited by ", ". The whole lot then needs to echo out. Here's what I have so far:

Levenstein for <b><?php echo $_POST["source"]; ?></b> and <b><?php echo $_POST["target"]; ?></b>:

<?php
$string5 = $_POST["source"];
$string6 = $_POST["target"];
$array6 = explode(', ',$string6); 
    
echo levenshtein("$string5","$array6");
?>

Solution

  • You'd use a foreach loop (a for loop would be fine too). Try:

    Levenstien for <b><?php echo $_POST["source"]; ?></b> and <b><?php echo $_POST["target"]; ?></b>:
    
    <?php
    $string5 = $_POST["source"];
    $string6 = $_POST["target"];
    $array6 = explode(', ',$string6); 
    
    foreach ($array6 as $derp)
    {
        echo $string5, "/", $derp, ": ", levenshtein($string5, $derp), "<br>";
    }
    
    ?>
    

    To output in order by score, use this:

    Levenstien for <b><?php echo $_POST["source"]; ?></b> and <b><?php echo $_POST["target"]; ?></b>:
    
    <?php
    $string5 = $_POST["source"];
    $string6 = $_POST["target"];
    $array6 = array_map('trim', explode(',',$string6));
    $doop = array();
    
    foreach ($array6 as $derp)
    {
        doop[$derp] = levenshtein($string5, $derp);
    }
    
    arsort($doop); // sorts highest element first
    
    foreach ($words as $key => $value)
    {
        echo sprintf('%s / %s: %s<br />', $string5, $key, $value);
    }
    
    ?>