0

I have two arrays and I want to delete the same values between the two for example

  $array1 = array(1,2,3,4,5,6)
  $array2 = array(5,6,7,8,9,10)

would have the result

  $array = array(1,2,3,4,7,8,9,10)

I tried

$array = array_unique(array_merge($array1, $array2));

But clearly that just deleted duplicates leaving the matched values, as single values. Is there a quick way to do this or will this have to be done using a function?

Sorry guys, clearly I don't understand arrays. Here are the actual arrays and result of suggestions at the bottom. result should be Coffee and General.

  array(4) {
    [0]=>
    NULL
    [1]=>
    string(4) "Milk"
    [3]=>
    string(6) "Coffee"
    [6]=>
    string(8) "Sweetner"
  }


  array(4) {
    [0]=>
    NULL
    [1]=>
    string(8) "Sweetner"
    [3]=>
    string(4) "MIlk"
    [9]=>
    string(7) "General"
  }


  array(4) {
    [1]=>
    string(4) "Milk"
    [2]=>
    string(6) "Coffee"
    [6]=>
    string(4) "MIlk"
    [7]=>
    string(7) "General"
  }
3
  • you can find the common values (array_intersect) in two arrays and then delete those values from both the arrays Commented Aug 24, 2012 at 12:47
  • 2
    What happened to 3 in the resulting array? Commented Aug 24, 2012 at 12:55
  • Clearly you have a problem with your expectations. The result is correct, only null and Sweetner exist in both arrays and are properly filtered out. The rest are the unique values of both arrays. Commented Aug 24, 2012 at 13:32

4 Answers 4

4

A combination of array_diff(), array_merge() and array_intersect() is what you need here:

$array = array_diff(
  array_merge($array1, $array2),
  array_intersect($array1, $array2)
);

See it working

Sign up to request clarification or add additional context in comments.

Comments

2

Try with array_intersect

$intersect = array_intersect($array1, $array2);
$array     = array_diff(array_merge($array1, $array2), $intersect);

Comments

1

You want the merge of the difference of both arrays, where "difference" means "values that do not exist in the other array":

$array = array_merge(array_diff($array1, $array2), array_diff($array2, $array1));

Comments

0

Only for fun and when your arrays contains string and integer values only:

$array = array_keys(array_flip($array1) + array_flip($array2));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.