The array_uintersect_uassoc() function in PHP is used to compute the intersection of arrays, comparing both the data and keys using user-defined comparison functions. This is particularly helpful when you need fine control over how the elements and keys are compared between multiple arrays.
array_uintersect_uassoc(array $array1, array ...$arrays, callable $value_compare_func, callable $key_compare_func): array
$array1 = ['a' => 'apple', 'b' => 'banana', 'c' => 'cherry'];
$array2 = ['a' => 'apple', 'b' => 'berry', 'c' => 'cherry'];
$result = array_uintersect_uassoc(
$array1,
$array2,
function($a, $b) {
return strcmp($a, $b);
},
function($a, $b) {
return strcmp($a, $b);
}
);
print_r($result);
Output:
Array
(
[a] => apple
[c] => cherry
)
$array1 = ['A' => 'apple', 'B' => 'banana', 'C' => 'cherry'];
$array2 = ['a' => 'apple', 'b' => 'berry', 'c' => 'cherry'];
$result = array_uintersect_uassoc(
$array1,
$array2,
function($a, $b) {
return strcmp($a, $b);
},
function($a, $b) {
return strcasecmp($a, $b); // Case-insensitive key comparison
}
);
print_r($result);
Output:
Array
(
[A] => apple
[C] => cherry
)
$array1 = ['apple' => 'red', 'banana' => 'yellow', 'cherry' => 'red'];
$array2 = ['apple' => 'green', 'grape' => 'purple', 'cherry' => 'dark red'];
$result = array_uintersect_uassoc(
$array1,
$array2,
function($a, $b) {
return strlen($a) - strlen($b); // Compare values by length
},
function($a, $b) {
return strlen($a) - strlen($b); // Compare keys by length
}
);
print_r($result);
Output:
Array
(
[cherry] => red
)
The array_uintersect_uassoc() function provides fine-grained control for intersecting arrays based on custom comparison rules for both values and keys. It is particularly useful when working with associative arrays where the comparison logic for keys and values can differ.