How to find out the difference in an associative array using array_diff_uassoc() function?
In PHP, array_diff_uassoc() is a function that compares two associative arrays and returns the difference between them. It not only compares based on the key values of the array, but also allows custom comparison functions to determine whether the values are equal. This function is very suitable for handling multi-dimensional arrays or when special comparison logic is required.
The basic syntax of array_diff_uassoc() is as follows:
array_diff_uassoc(array $array1, array $array2, callable $key_compare_func): array
$array1 : The first associative array.
$array2 : The second associative array.
$key_compare_func : A callback function used to compare array keys. This function takes two parameters and returns an integer value, indicating their comparison results.
Suppose we have two associative arrays, we want to find out the difference between them, specifically, we want to find out the elements that are in the first array and not in the second array.
<?php
$array1 = array(
"a" => "apple",
"b" => "banana",
"c" => "cherry"
);
$array2 = array(
"a" => "apple",
"b" => "blueberry"
);
$result = array_diff_uassoc($array1, $array2, "key_compare");
print_r($result);
function key_compare($key1, $key2) {
return strcmp($key1, $key2);
}
?>
We define two associative arrays $array1 and $array2 .
Using the array_diff_uassoc() function, we pass in two arrays and a comparison function key_compare .
The key_compare function uses strcmp() to compare the alphabetical order of keys. Its return value determines the relative order of the two keys:
If a negative number is returned, it means that $key1 is less than $key2 .
If zero is returned, it means $key1 is equal to $key2 .
If a positive number is returned, it means that $key1 is greater than $key2 .
The array_diff_uassoc() function will return elements in $array1 , which have different corresponding keys or values in $array2 .
Array
(
[c] => cherry
)
As can be seen from the above output, array_diff_uassoc() returns "c" => "cherry" in $array1 , because this element does not find the corresponding key "c" in $array2 .
array_diff_uassoc() allows you to customize comparison functions, not just simple string or numeric comparisons. For example, you can compare key-value pairs based on specific logic. For example, suppose we want to compare the length of the array value instead of the literal value:
<?php
$array1 = array(
"a" => "apple",
"b" => "banana",
"c" => "cherry"
);
$array2 = array(
"a" => "apple",
"b" => "banana",
"c" => "pear"
);
$result = array_diff_uassoc($array1, $array2, "length_compare");
print_r($result);
function length_compare($key1, $key2) {
return strlen($key1) - strlen($key2);
}
?>
Suppose we are working on an array containing URLs and need to use array_diff_uassoc() to find out the differences. Here is a specific example where we replace the domain name with m66.net :