views:

35

answers:

3

Here's the problem: I have words I entered via a textarea. I put each word in an entry. i.e words are in an array. On the other hand, I got a wordlist, in which words are separated by newline, I put each word in another array, too.

Now I want to check if $words_entered[$i] = any (and which) of the array $wordlist.

Thanks in advance!

+1  A: 

Use the in_array function:

if (in_array($words_entered[$i], $wordlist))
{
  echo 'The word ' . $words_entered[$i] . ' is in the wordlist' . '<br />';
}
Sarfraz
+3  A: 

If you want the results in the list:

$intersection = array_intersect($words_entered,explode("\n",$wordlist));

If you want the results NOT in the list:

$diff = array_diff($words_entered,explode("\n",$wordlist));
Wrikken
A: 

I would check on-the fly...


$dic=explode("\n",file_get_contents('dictionary.txt'));

$words=array();
$words=explode(" ",strtolower(file_get_contents('text.txt'));

foreach($words as $index=>$word) {
  if(in_array($word,$dic)) {
    // do something
  } else {
    // do something else
  }
}

if the text is huge i would speed up the comparison by replacing in_array with isset like this...


$dic_temp=explode("\n",file_get_contents('dictionary.txt'));
$dic=array();
foreach($dic_temp as $k=>$v) {
  $dic[$k]=1;
}
unset($dic_temp);

$words=array();
$words=explode(" ",strtolower(file_get_contents('text.txt'));

foreach($words as $index=>$word) {
  if(isset($dic[$word])) {
    // do something
  } else {
    // do something else
  }
}
vlad b.