Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

php - Getting unique values from 2 arrays

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...