The array_intersect_uassoc Function
The array_intersect_uassoc
function compares arrays and returns elements that are present in all arrays, using a callback function for key comparison. The first parameter is the main array, the subsequent ones are arrays for comparison, and the last parameter is the callback function for key comparison.
Syntax
array_intersect_uassoc(array $array1, array $array2, ..., callable $key_compare_func): array;
Example
Let's compare two arrays with key check via a user-defined function:
<?php
$array1 = ['a' => 1, 'b' => 2, 'c' => 3];
$array2 = ['a' => 1, 'b' => 5, 'c' => 3];
function compareKeys($a, $b) {
return $a <=> $b;
}
$res = array_intersect_uassoc($array1, $array2, 'compareKeys');
print_r($res);
?>
Code execution result:
['a' => 1, 'c' => 3]
Example
Let's compare three arrays with a user-defined key comparison function:
<?php
$array1 = [1 => 'a', 2 => 'b', 3 => 'c'];
$array2 = [1 => 'a', 4 => 'b', 3 => 'd'];
$array3 = [1 => 'a', 3 => 'e'];
function keyCompare($key1, $key2) {
if ($key1 == $key2) {
return 0;
}
return ($key1 < $key2) ? -1 : 1;
}
$res = array_intersect_uassoc($array1, $array2, $array3, 'keyCompare');
print_r($res);
?>
Code execution result:
[1 => 'a']
See Also
-
the
array_intersect
function,
which computes the intersection of arrays without key check -
the
array_intersect_assoc
function,
which computes the intersection of arrays with key check -
the
array_uintersect_assoc
function,
which computes the intersection of arrays with key check via a callback function