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

Categories

Is there any function in PHP which will give an array of uncommon values from two or more arrays?

For example:

$array1 = array( "green", "red", "blue");
$array2 = array( "green", "yellow", "red");
....
$result = Function_Needed($array1, $array2,...);
print_r($result);

Should give the output:

array("blue", "yellow", ...);
See Question&Answers more detail:os

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

1 Answer

Use array_diff and array_merge:

$result = array_merge(array_diff($array1, $array2), array_diff($array2, $array1));

Here's a demo.

For multiple arrays, combine it with a callback and array_reduce:

function unique(&$a, $b) {
    return $a ? array_merge(array_diff($a, $b), array_diff($b, $a)) : $b;
}

$arrays = array(
    array('green', 'red', 'blue'),
    array('green', 'yellow', 'red')
);

$result = array_reduce($arrays, 'unique');

And here's a demo of that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...