I have 2 arrays that I\'m trying to get the unique values only from them. So I\'m not just trying to remove duplicates, I\'m actually trying to remove both duplicates.
The other answers are on the right track, but array_diff only works in one direction -- ie. it returns the values that exist in the first array given that aren't in any others.
What you want to do is get the difference in both directions and then merge the differences together:
$array1 = array(10, 15, 20, 25);
$array2 = array(10, 15, 100, 150);
$output = array_merge(array_diff($array1, $array2), array_diff($array2, $array1));
// $output will be (20, 25, 100, 150);
Here is the code to do it. It may be able to be optimized, but you get the idea:
$array1 = array(10, 15, 20, 25);
$array2 = array(10, 15, 100, 150);
$new_array = array();
foreach($array1 as $value) {
if(!in_array($value, $array2)) {
array_push($new_array, $value);
}
}
foreach($array2 as $value) {
if(!in_array($value, $array1)) {
array_push($new_array, $value);
}
}
print_r($new_array);
To use array_diff, you would have to do:
$array1 = array(10, 15, 20, 25);
$array2 = array(10, 15, 100, 150);
$out1 = array_diff($array1, $array2);
$out2 = array_diff($array2, $array1);
$output = array_merge($out1, $out2);
print_r($output);
Another good solution is this:
$array1 = array(10, 15, 20, 25);
$array2 = array(10, 15, 100, 150);
$output = array_diff(array_merge($array1, $array2), array_intersect($array1, $array2));
// $output will be (20, 25, 100, 150);
The array_diff()
(manual) function can be used to find the difference between two arrays:
$array1 = array(10, 20, 40, 80);
$array2 = array(10, 20, 100, 200);
$diff = array_diff($array1, $array2);
// $diff = array(40, 80, 100, 200);
You can pass as many arrays as you want to the function, it is not just limited to two arrays.
Try following code it works fine for numbers,String and every condition
The following Logic will only works for numbers.
$array1 = array(10, 15, 20, 25);
$array2 = array(10, 15, 100, 150);
$output = array_merge(array_diff($array1, $array2), array_diff($array2, $array1));
The following logic will work fine for any condition
$a1 = array('1@gmail.com');
$a2 = array('1@gmail.com','2@gmail.com');
$new_array=array_merge($a1,$a2);
$unique=array_unique($new_array);
Thanks
Not to detract from Daniel Vandersluis's answer, but to add to it...
What you're looking for is basically an XOR operation of the arrays. To that end, "merlinyoda at dorproject dot net" provided the following routine, in a comment on http://php.net/manual/en/function.array-diff.php :
<?php
function array_xor ($array_a, $array_b) {
$union_array = array_merge($array_a, $array_b);
$intersect_array = array_intersect($array_a, $array_b);
return array_diff($union_array, $intersect_array)
}
?>
This function takes a different approach to calculating the XOR.