The array_udiff_uassoc() function in PHP is used to compare arrays and compute the difference using user-defined comparison functions for both data and keys. This is especially useful when you need fine-grained control over how values and keys are compared between arrays.
array_udiff_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' => 'grape', 'c' => 'cherry'];
$result = array_udiff_uassoc(
$array1,
$array2,
function($a, $b) {
return strcmp($a, $b);
},
function($a, $b) {
return strcmp($a, $b);
}
);
print_r($result);
Output:
Array
(
[b] => banana
)
$array1 = ['A' => 'apple', 'B' => 'banana', 'C' => 'cherry'];
$array2 = ['a' => 'apple', 'b' => 'grape', 'C' => 'cherry'];
$result = array_udiff_uassoc(
$array1,
$array2,
function($a, $b) {
return strcmp($a, $b);
},
function($a, $b) {
return strcasecmp($a, $b);
}
);
print_r($result);
Output:
Array
(
[B] => banana
)
$array1 = ['apple' => 'red', 'banana' => 'yellow', 'cherry' => 'red'];
$array2 = ['apple' => 'green', 'grape' => 'purple', 'cherry' => 'dark red'];
$result = array_udiff_uassoc(
$array1,
$array2,
function($a, $b) {
return strlen($a) - strlen($b);
},
function($a, $b) {
return strlen($a) - strlen($b);
}
);
print_r($result);
Output:
Array
(
[apple] => red
[banana] => yellow
[cherry] => red
)
The array_udiff_uassoc() function provides the flexibility to compare arrays with custom rules for both values and keys. Whether you need to perform case-insensitive comparisons or use more complex logic like length-based comparisons, this function helps you maintain fine control over the comparison process. It's especially useful for dealing with associative arrays where both data and key differences matter.
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.