Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting unique values from 2 arrays

Tags:

arrays

php

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?

like image 929
lok Avatar asked Aug 17 '10 22:08

lok


People also ask

How can I get unique values from two arrays in PHP?

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);


1 Answers

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);
like image 166
Daniel Vandersluis Avatar answered Oct 02 '22 01:10

Daniel Vandersluis