array_diff

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tommy1987
Forum Commoner
Posts: 92
Joined: Tue Feb 21, 2006 8:35 pm

array_diff

Post 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.
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post 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
)
tommy1987
Forum Commoner
Posts: 92
Joined: Tue Feb 21, 2006 8:35 pm

Post 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.
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

Use a foreach
tommy1987
Forum Commoner
Posts: 92
Joined: Tue Feb 21, 2006 8:35 pm

Post 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?
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

element ids are known as keys in php and yes, try array_values()
Post Reply