2

I'm trying to compare two arrays using this code:

           $diff = array_diff($selected, $checkboxes);

            echo '<br>selected:';
            print_r($selected);
            echo '<br>original:';
            print_r($checkboxes);
            echo '<br>difference:';
            print_r($diff);

The strange thing is though this results in the following:

selected:Array ( [0] => Forum1 [1] => Forum3 [2] => Furniture ) 
original:Array ( [0] => Forum1 [1] => Forum3 [2] => forum4 [3] => Furniture [4] => Nieuwforum ) 
difference:Array ( [0] => Forum1 [1] => Forum3 [2] => Furniture )

It seems like the array_diff function only copies the 'selected'array. I tried several things that where posted in similar question like for instance using array_diff_assoc but it doesn't matter.

Anyone knows what goes wrong?

2 Answers2

1

As mention in array_diff.

Returns an array containing all the entries from array1 that are not present in any of the other arrays

$diff = array_diff($checkboxes,$selected);

Codepad Demo.

Rikesh
  • 26,156
  • 14
  • 79
  • 87
  • So that would mean, I just have to switch $checkboxes and $selected right? I had already tried that, but this results in: selected:Array ( [0] => Forum1 [1] => Furniture [2] => Nieuwforum ) original:Array ( [0] => Forum1 [1] => Forum3 [2] => forum4 [3] => Furniture [4] => Nieuwforum ) difference:Array ( [0] => Forum1 [1] => Forum3 [2] => forum4 [3] => Furniture [4] => Nieuwforum ) So it still doesn't output the difference only the whole list.. – user1803370 Mar 27 '13 at 08:04
  • Yes you need to switch your array. Check the demo I have give in my answer. – Rikesh Mar 27 '13 at 08:06
  • I checked it, but this also doesn't provide the difference between the two arrays. It provides the matches instead. I mean: 'Returns an array containing all the entries from array1 that are NOT present in any of the other arrays' Till now all solutions only return entries that are present in the other array – user1803370 Mar 27 '13 at 08:21
0

I think you are searching for array_intersect.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Vishnu T Asok
  • 244
  • 4
  • 15