I have a string value held in a var, I want to compare it against a array and print the array number that is the nearest match whilst being case sensitive.
so the question is how do I find the nearest match within my array to my var $bio
in this case it would be 4
I have seen pregmatch but am unsure on how to use it in this case.
Code I have
<?php
$bio= "Tom, male, spain";
$list= array(
1 => array("Tom", "male", "UK"),
8 => array("bob", "Male", "spain"),
4 => array("Tom", "male", "spain"),
9 => array("sam", "femail", "United States")
);
function best_match($bio, $list)
{
}
I was thinking something like thinking
$matches = preg_grep ($bio, $list);
print_r ($matches);
Another way using array_intersect:
$bio= "Tom, male, spain";
$list= array(
1 => array("Tom", "male", "UK"),
8 => array("bob", "Male", "spain"),
4 => array("Tom", "male", "spain"),
9 => array("sam", "femail", "United States")
);
function best_match($bio, $list) {
$arrbio = explode(', ', $bio);
$max = 0;
$ind = 0;
foreach($list as $k => $v) {
$inter = array_intersect($arrbio, $v);
if (count($inter) > $max) {
$max = count($inter);
$ind = $k;
}
}
return [$ind, $max];
}
list($index, $score) = best_match($bio, $list);
echo "Best match is at index: $index with score: $score
";
Output:
Best match is at index: 4 with score: 3
This may be a job for similar text, i.e:
$bio= "Tom, male, spain";
$list = array(
1 => array("Tom", "male", "UK"),
8 => array("bob", "Male", "spain"),
4 => array("Tom", "male", "spain"),
9 => array("sam", "femail", "United States")
);
$percent_old = 0;
foreach ($list as $key => $value ) # loop the arrays
{
$text = implode(", ", $value); # implode the array to get a string similar to $bio
similar_text($bio, $text, $percent); # get a percentage of similar text
if ($percent > $percent_old) # check if the current value of $percent is > to the old one
{
$percent_old = $percent; # assign $percent to $percent_old
$final_result = $key; # assign $key to $final_result
}
}
print $final_result;
# 4