rosey85uk
rosey85uk

Reputation: 95

similar_text() to compare product names to a given string

I am currently trying to play about with some PHP that will compare an array of words/phrases with a user provided word and then return just the word which has the highest percentage..

My code so far is (for the sake of testing):

<?php

$CRProductName = strtoupper("Product 30");

$XProdNames = array("Product 1","Product 2", "Product 300", "Not a product");

echo "Checking product matches for: ".$CRProductName."<br /><br />";

foreach ($XProdNames as $ProductName) {
    similar_text($CRProductName,strtoupper($ProductName), $p);
    echo "Percentage:".$p."%<br />";

}

?>

This outputs the following:

Checking product matches for: PRODUCT 30

Percentage:84.2105263158% 
Percentage:84.2105263158%
Percentage:95.2380952381% 
Percentage:60.8695652174%

Which is great and it works, however I would just like it to return the product name with the highest percentage in the results?

Can anyone advise on a good route for me to take?

I tried adding an IF statement to check the value of $p, but the highest percentage may differ every time.

I converted all to uppercase just to make sure it is marking the similarity by content and not by case.

Thanks,

Upvotes: 0

Views: 129

Answers (2)

Dragos Costin Ionita
Dragos Costin Ionita

Reputation: 14

It's very simple. Just use an if statement to check for the highest value in the foreach loop. then echo the highest value. Here's your code with the minor change:

<?php

$CRProductName = strtoupper("Product 30");

$XProdNames = array("Product 1","Product 2", "Product 300", "Not a product");

echo "Checking product matches for: ".$CRProductName."<br /><br />";

$pHighest = 0;
foreach ($XProdNames as $ProductName) {
similar_text($CRProductName,strtoupper($ProductName), $p);
    if ($p > $pHighest) {
      $pHighest = $p;
    }
}
echo "Percentage:".$pHighest."%<br />";

?>

Upvotes: 0

MiDri
MiDri

Reputation: 747

<?php

$CRProductName = strtoupper("Product 30");

$XProdNames = array("Product 1","Product 2", "Product 300", "Not a product");

echo "Checking product matches for: ".$CRProductName."<br /><br />";

$bestMatch = array('score' => 0, 'name' => 'None');

foreach ($XProdNames as $ProductName) {
    $p = 0;
    similar_text($CRProductName,strtoupper($ProductName), $p);
    echo "Percentage:".$p."%<br />";

    if($p > $bestMatch['score'])
    {
        $bestMatch = array('score' => $p, 'name' => $ProductName);
    }

}

print_r($bestMatch);
?>

you could always run simlar_text a few times in each loop and average the results as well if you're getting fluxing results.

Upvotes: 1

Related Questions