array_uintersect(): intersection of arrays with Custom Comparison

array_uintersect(): custom value intersection

array_uintersect() finds common values using a user-supplied value comparison callback and preserves keys from the first array.

$first = [10, 20, 30];
$second = [10, 25, 30];
$result = array_uintersect($first, $second, fn($a, $b) => $a <=> $b);
print_r($result);

Return an integer comparison result from the callback rather than true or false.

The array_uintersect() function in PHP returns the intersection of arrays, using a custom callback function to compare values. It is useful when the comparison between array elements requires custom logic.

Syntax

array_uintersect(array $array1, array $array2, callable $callback): array

Example 1: Simple Intersection with Case-Insensitive Comparison

function caseInsensitiveCompare($a, $b) {
    return strcmp(strtolower($a), strtolower($b));
}

$array1 = ['APPLE', 'BANANA', 'CHERRY'];
$array2 = ['apple', 'ORANGE', 'cherry'];

$result = array_uintersect($array1, $array2, 'caseInsensitiveCompare');
print_r($result);
Output
Array
(
    [0] => APPLE
    [2] => CHERRY
)

Example 2: Intersection of Numeric Arrays with Custom Comparison

function numCompare($a, $b) {
    return $a - $b;
}

$array1 = [1, 2, 3, 4];
$array2 = [3, 4, 5, 6];

$result = array_uintersect($array1, $array2, 'numCompare');
print_r($result);
Output
Array
(
    [2] => 3
    [3] => 4
)

Conclusion

The array_uintersect() function provides flexibility in finding intersections between arrays by allowing custom comparison logic, making it highly versatile for different use cases.
array_intersect(): Intersection of two or more arrays Difference between arrays considering values
Array REFERENCE


Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer