Page 1 of 1

array_diff

Posted: Mon Feb 05, 2007 7:40 pm
by tommy1987
I have two arrays, one containing omitted words and one containing a search term. I want an array of the search terms minus the omitted words if they exist.

e.g. this is my code:

Code: Select all

/* Return the word matches in question which ARENT in omitted words */
  $validWords = array();
  $validWords = array_diff($questionWords, $omittedWords);
  return $validWords;
Both the arrays to be input are definitely containing the correct values, but I only seem to get three values maximum stored in the $validWords array created. Its a very strange problem.

Posted: Mon Feb 05, 2007 8:33 pm
by Ollie Saunders
*shrug*

It works for me

Code: Select all

$question = array('a', 'b', 'c');
$omit = array('b');
echo '<pre>', print_r(array_diff($question, $omit), true);

Code: Select all

Array
(
    [0] => a
    [2] => c
)

Posted: Tue Feb 06, 2007 4:17 am
by tommy1987
I am then using this to output the array, but since the indexes are not consistent i.e. they dont start at 0 and go up, it is proving a problem.

Code: Select all

for($i=0;$i<sizeof($validWords);$i++) {
          echo '<br/>'.$validWords[$i].' ';
        }
i.e. For the above code sizeof($validWords) would equal 3 if there are three words, but the id's of the words might not be 0, 1, 2 as the for loop would check. Hence my problem.

Posted: Tue Feb 06, 2007 4:23 am
by Ollie Saunders
Use a foreach

Posted: Tue Feb 06, 2007 4:44 am
by tommy1987
Is there a way to resort the element ID's according to 0,1,2,3,4,5 instead of the random ones?

Posted: Tue Feb 06, 2007 4:57 am
by Ollie Saunders
element ids are known as keys in php and yes, try array_values()