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
524 views
in Technique[技术] by (71.8m points)

php - Get uncommon values from two or more arrays

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

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

1 Answer

0 votes
by (71.8m points)

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.


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

...