I'm looking for the opposite of the function array_intersect, basically a function that returns the element that are not present in each of the provided arrays.
Example:
$a1 = array(1, 2, 3);
$a2 = array(2, 3, 4);
$result = array(1, 4);
I know how to do it programmatically (I just have two array so array_merge(array_diff($a1, $a2), array_diff($a2, $a1)) would do the job), but I'd like to know whether there's a built-in function that I can't find.
Thanks.
Since array_diff($a, $b) !== array_diff($b, $a)
the inverse of array_intersect is:
array_merge(array_diff($a,$b), array_diff($b,$a));
Here it is in a PHPUnit test format:
class ArrayInverseTest {
function testInverseArrayIntersect() {
$a = array(1, 2, 3);
$b = array(2, 3, 4);
$this->assertEquals(
array_values(array(1, 4)),
array_values(array_merge(array_diff($a, $b), array_diff($b, $a)))
);
}
}
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