Eliminating duplicate entries in an array


array_flip() magic

array array_flip ( array trans ) – Exchanges all keys with their associated values in an array

array_flip() returns an array in flip order, i.e. keys from trans become values and values from trans become keys.

< ?php
  /* In this example we are removing duplicate search keywords
     from a search form. */

  // extract the posted data from a search form
  // $search = extract($_POST['search']);
  // Lets assume the search words are as follows
  $search = "Men are from mars and women are from venus";

  // Explode the sentence at each space character as we know
  // each word is distinguised by a space.
  // $words variable will become an array of the search words.
  $words = explode(" ", trim( $search ) );

  //Ignore multiple inputs of same word:
  $words = array_flip($words);
?>

Lets now dump the array and see what it holds after the first array flip

< ?php
  // Dumping to see what the $words array holds
  print_r($words);
?>
Array
(
    [Men] => 0
    [are] => 6
    [from] => 7
    [mars] => 3
    [and] => 4
    [women] => 5
    [venus] => 8
)

As you can see from the above dump, we have lost the duplicate words we had in the search string. But ofcourse the key-value pairs are now reversed. So the next step we do is to reverse the key-value pairs by doing an other array_flip()

< ?php
  // array_flip again to get the key-value pairs in right order
  $words = array_flip($words);
?>

Lets see now what the status of the array $words is

< ?php
  print_r($words);
?>
Array
(
    [0] => Men
    [6] => are
    [7] => from
    [3] => mars
    [4] => and
    [5] => women
    [8] => venus
)

Now we have an array which has no duplicate entries in it. We can now use that array to do a search in the database and not worrying if the user has inputted duplicate search words. etc.

You can further improve on this by adding a stop-word list to ignore common words like “and is the”.. etc.

This entry was posted in PHP. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">