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.
So if I'm getting the 2 arrays like this:
$array1 = array();
$array2 = array();
foreach($values1 as $value1){ //output: $array1 = 10, 15, 20, 25;
$array1[] = $value1;
}
foreach($values2 as $value2){ //output: $array2 = 10, 15, 100, 150;
$array2[] = $value2;
}
The final output I'm looking for is
$output = 20, 25, 100, 150;
Any neat way to getting this done?
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With