Current Location: Home> Latest Articles> How to use the array_diff_uassoc function in PHP to implement key comparisons that ignore case?

How to use the array_diff_uassoc function in PHP to implement key comparisons that ignore case?

M66 2025-06-06

In PHP, the array_diff_uassoc function is used to compare two arrays, returning all parts of the first array that are different from the second array. The main feature of this function is that it allows us to provide a custom comparison function for comparing keys to arrays. By combining custom comparison functions, we can implement key comparisons that ignore upper and lower case.

This article will introduce how to use the array_diff_uassoc function to implement key comparisons that ignore case.

1. Introduction to array_diff_uassoc function

The syntax of the array_diff_uassoc function is as follows:

 array_diff_uassoc(array $array1, array $array2, callable $key_compare_func): array
  • $array1 and $array2 : Two arrays to compare.

  • $key_compare_func : Custom key comparison function for comparing two array keys.

This function returns an array containing key-value pairs that exist in $array1 but not in $array2 .

2. Ignore case comparison

To implement key comparisons that ignore case, we need to write a custom comparison function that converts the keys to uniform lowercase or uppercase and then compares. Here is a code example of the implementation:

 <?php

// Custom key comparison function:Ignore case
function case_insensitive_key_compare($key1, $key2) {
    return strcasecmp($key1, $key2);
}

// Define two arrays
$array1 = [
    "first" => "apple",
    "second" => "banana",
    "Third" => "cherry"
];

$array2 = [
    "FIRST" => "apple",
    "second" => "grape",
    "third" => "kiwi"
];

// use array_diff_uassoc Comparison of two arrays,Ignore case
$result = array_diff_uassoc($array1, $array2, 'case_insensitive_key_compare');

// Output result
print_r($result);

?>

3. Code parsing

  • Custom comparison function : case_insensitive_key_compare uses PHP's built-in strcasecmp function, which compares two strings and ignores case. If the two strings are equal, strcasecmp will return 0 , otherwise it will return a non-zero value.

  • Array definition : $array1 and $array2 are the two arrays we want to compare. Note that their key names differ in case.

  • Call array_diff_uassoc : We pass case_insensitive_key_compare into array_diff_uassoc as a custom comparison function, thereby implementing key comparisons that ignore case.

  • Output : Finally, the $result array contains items in $array1 whose key values ​​do not match the $array2 key values.

4. Output result

When running the above code, the output will be as follows:

 Array
(
    [third] => cherry
)

In this example, although the key in $array1 is "Third" and the key in $array2 is "third" , they are considered the same since we use a comparison method that ignores case, so "third" => "cherry" is kept in the result array.