entropid
entropid

Reputation: 6239

Opposite of array_intersect

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.

Upvotes: 4

Views: 3338

Answers (4)

willoller
willoller

Reputation: 7330

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

Upvotes: 6

dynamic
dynamic

Reputation: 48131

No there isn't builtin for that

I believe a language will never provide such a builtin function

Upvotes: 1

Joni
Joni

Reputation: 111329

Are you looking for array union? http://es.php.net/manual/en/language.operators.array.php

Upvotes: 1

user703016
user703016

Reputation: 37975

It's not built in. Note that you can improve your solution:

array_merge($a1, array_diff($a2, $a1));

Upvotes: 2

Related Questions