PHP Array
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