0

Two PHP arrays:

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

Now how can I end up with an array like this:

$array3 = array(6,7,8,9,10);

4 Answers 4

6

With array_diff:

$array3 = array_diff($array2, $array1);
Sign up to request clarification or add additional context in comments.

2 Comments

But beware the sequence: array_diff($array1, $array2); would return an empty array!
@DanLee: IMHO that's not that sneaky a trap because "taking the difference" (e.g. subtraction) is generally a non-commutative operation.
0

use array_diff

$array3 = array_diff($array2, $array1)

Comments

0

As array_diff returns a relative complement you can use this code for a full diff, where it doesn't matter on which side the diff should be made:

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

Comments

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

$output = array_merge(array_diff($array1, $array2), array_diff($array2, $array1));
print_r($output);

Output:

Array ( [0] => 6 [1] => 7 [2] => 8 [3] => 9 [4] => 10 ) 

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.