array_diff / array_intersect family

array_diff(array $array, array ...$arrays): array — array_intersect(array $array, array ...$arrays): array

Two set-operation families: difference (diff) and intersection (intersect), each with key / assoc / uassoc / ukey comparison variants. Values compare loosely as strings, keys and order are kept — the complete PHP array set-operation toolbox.

C C23

C23
#include <stdio.h>

int main(void) {
    int a[] = {1, 2, 3, 2, 4};
    int b[] = {2, 5};
    size_t na = sizeof a / sizeof a[0], nb = sizeof b / sizeof b[0];
    printf("diff: [");
    int first = 1;
    for (size_t i = 0; i < na; i++) { // hand-written diff: nested membership scan
        int found = 0;
        for (size_t j = 0; j < nb; j++) if (a[i] == b[j]) { found = 1; break; }
        if (!found) { printf(first ? "%d" : ", %d", a[i]); first = 0; }
    }
    printf("]\nintersect: [");
    first = 1;
    for (size_t i = 0; i < na; i++) {
        int found = 0;
        for (size_t j = 0; j < nb; j++) if (a[i] == b[j]) { found = 1; break; }
        if (found) { printf(first ? "%d" : ", %d", a[i]); first = 0; }
    }
    printf("]\n");
    return 0;
}
Output
diff: [1, 3, 4]
intersect: [2, 2]

C++ C++26

C++26
#include <iostream>
#include <vector>

int main() {
    std::vector<int> a = {1, 2, 3, 2, 4};
    std::vector<int> b = {2, 5};
    std::vector<int> diff, inter;
    for (int x : a) { // hand-written scan keeps every matching occurrence (multiset semantics)
        bool found = false;
        for (int y : b) if (x == y) { found = true; break; }
        (found ? inter : diff).push_back(x);
    }
    auto show = [](const char *tag, const std::vector<int> &v) {
        std::cout << tag << ": [";
        for (size_t i = 0; i < v.size(); ++i) {
            if (i) std::cout << ", ";
            std::cout << v[i];
        }
        std::cout << "]\n";
    };
    show("diff", diff);
    show("intersect", inter);
    return 0;
}
Output
diff: [1, 3, 4]
intersect: [2, 2]

C# v11.0.100

v11.0.100
var a = new List<int> { 1, 2, 3, 2, 4 };
var b = new List<int> { 2, 5 };
var diff = a.Except(b).ToList();     // set difference: also dedupes
var inter = a.Intersect(b).ToList(); // set intersection: dedupes too
Console.WriteLine($"diff: [{string.Join(", ", diff)}]");
Console.WriteLine($"intersect: [{string.Join(", ", inter)}]");
Output
diff: [1, 3, 4]
intersect: [2]

Go v1.27.4

v1.27.4
package main

import "fmt"

func main() {
    a := []int{1, 2, 3, 2, 4}
    b := []int{2, 5}
    inB := map[int]bool{}
    for _, v := range b {
        inB[v] = true
    }
    var diff, inter []int
    for _, v := range a { // one pass builds both, order and duplicates preserved
        if inB[v] {
            inter = append(inter, v)
        } else {
            diff = append(diff, v)
        }
    }
    fmt.Println("diff:", diff)
    fmt.Println("intersect:", inter)
}
Output
diff: [1 3 4]
intersect: [2 2]

Java v27.0.1

v27.0.1
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> a = new ArrayList<>(Arrays.asList(1, 2, 3, 2, 4));
        List<Integer> b = List.of(2, 5);
        List<Integer> diff = new ArrayList<>(a);
        List<Integer> inter = new ArrayList<>(a);
        diff.removeAll(b);  // keeps every surviving occurrence: [1, 3, 4]
        inter.retainAll(b); // keeps every matching occurrence: [2, 2]
        System.out.println("diff: " + diff);
        System.out.println("intersect: " + inter);
    }
}
Output
diff: [1, 3, 4]
intersect: [2, 2]

JavaScript v26.13.1

v26.13.1
const a = [1, 2, 3, 2, 4];
const b = [2, 5];
const inB = new Set(b); // Set lookup is O(1); filter keeps duplicates
console.log("diff:", a.filter((x) => !inB.has(x)));
console.log("intersect:", a.filter((x) => inB.has(x)));
Output
diff: [ 1, 3, 4 ]
intersect: [ 2, 2 ]

PHP v8.6.0

v8.6.0
$a = [1, 2, 3, 2, 4];
$b = [2, 5];
// values are compared as strings (loose): "2" and 2 are the same here; keys are kept, so renumber
echo json_encode(array_values(array_diff($a, $b))), "\n";
echo json_encode(array_values(array_intersect($a, $b))), "\n";
Output
[1,3,4]
[2,2]

Python v3.15.2

v3.15.2
a = [1, 2, 3, 2, 4]
b = [2, 5]
in_b = set(b)  # set membership is O(1); the comprehension keeps duplicates
print("diff:", [x for x in a if x not in in_b])
print("intersect:", [x for x in a if x in in_b])
Output
diff: [1, 3, 4]
intersect: [2, 2]

Rust v1.99.1

v1.99.1
fn main() {
    let a = [1, 2, 3, 2, 4];
    let b = [2, 5];
    // contains() keeps duplicates: every matching occurrence survives
    let diff: Vec<i32> = a.iter().filter(|x| !b.contains(x)).copied().collect();
    let inter: Vec<i32> = a.iter().filter(|x| b.contains(x)).copied().collect();
    println!("diff: {:?}", diff);
    println!("intersect: {:?}", inter);
}
Output
diff: [1, 3, 4]
intersect: [2, 2]

TypeScript v26.13.1

v26.13.1
const a: number[] = [1, 2, 3, 2, 4];
const b: ReadonlySet<number> = new Set([2, 5]); // Set lookup is O(1); filter keeps duplicates
console.log("diff:", a.filter((x) => !b.has(x)));
console.log("intersect:", a.filter((x) => b.has(x)));
Output
diff: [ 1, 3, 4 ]
intersect: [ 2, 2 ]

Language differences

C: no built-in set container — a hand-written nested scan preserves order and duplicates; the engineering idiom pre-loads $b into a hash set for O(1) lookups (the tiny sample just scans directly).

C++: same as C — a hand-written order-preserving scan; 'std::unordered_set' is the O(1) membership choice in real code.

C#: 'Except'/'Intersect' are set semantics: the result is deduped (the duplicate 2 survives only once in the sample); use 'Where' filtering to keep order and duplicates.

Go: one pass over a map membership set builds both difference and intersection.

Java: 'removeAll'/'retainAll' mutate a list copy in place — order- and duplicate-preserving (multiset semantics, matching PHP).

JavaScript: 'filter' + 'Set' preserves order and duplicates.

PHP: two set-operation families — by value: 'array_diff'/'array_intersect'; by key: '_key' variants; by key+value: '_assoc' variants; '_uassoc'/'_ukey' compare keys with a callback; a leading 'u' (e.g. 'array_udiff') swaps in a callback for the value comparison. Values are compared with loose string equality '(string)$a === (string)$b': 2 equals "2", and classic pitfalls like '0' vs '"foo"' come from it; PHP has no built-in strict diff — strict set operations need 'array_filter' + 'in_array($v, $arr, true)' by hand. All variants keep the original keys.

Python: 'in'/'not in' use strict '==' type semantics (2 != "2"); the list comprehension preserves order and duplicates; native set ops 'set(a) - set(b)'/'&' dedupe and lose order.

Rust: 'contains' preserves order and duplicates; the 'HashSet' version dedupes.

TypeScript: same as JavaScript, with a 'ReadonlySet' annotation.