1

Is there any way in PHP to have an array and order it by most similar to a certain string.

For example:

$array = array("Bob", "Brad", "Britney");
$userinput = "Bradley123";

/*
function that changes the array to be
array("Brad","Britney","Bob")
from the most similar from the $userinput
*/
Achmed
  • 313
  • 3
  • 11

1 Answers1

1

I've done some research, here is a way that you could do it:

$array = array(0 => 'blue', 1 => 'reds', 2 => 'green', 3 => 'reds'); 
//Words to be searched from.

$res = array("percent" => "0", "word" => "N/A");
//Result, this is an array for the bellow loop to talk to.

foreach($array AS $ar){
  similar_text("red", $ar, $percent);

  //If it's more like the word, then replace the percentage with the percentage of similarity & word.
  if($percent > $res["percent"]){
    $res["percent"] = $percent;
    $res["word"] = $ar;
  }
}

//Echo out the most similar word.
echo $res["word"];

From what I could find, this was the only way possible for doing something like this.

FluxCoder
  • 1,266
  • 11
  • 22
  • I have tried to modify your code so that it would have all results in the same array but I keep on failing. Would you know of any way to bring each result into the array and have it ordered in the way of `most` similar to `least` similar – Achmed Sep 13 '16 at 19:14
  • I actually don't know if that is at all possible, I mean it would be but not without an extra for each loop. You could use something like a database as I said, but this script already does what you just asked, but does not put it into an array. – FluxCoder Sep 13 '16 at 19:18