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.
array_uintersect(array $array1, array $array2, callable $callback): array
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
)
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
)
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.