Current Location: Home> Latest Articles> How to use array_change_key_case() with array_diff_key() to compare case-independent key names of arrays?

How to use array_change_key_case() with array_diff_key() to compare case-independent key names of arrays?

M66 2025-04-24

In PHP, the key names of arrays are case-sensitive by default. This means that if you have two arrays, one with the keys of UserID and the other with userid , PHP will consider them to be two different keys. If you want to make case-independent comparisons of key names of an array, you can use array_change_key_case() and array_diff_key() in combination.

1. Function introduction

  • array_change_key_case(array $array, int $case = CASE_LOWER) : Convert all key names of the array to lowercase or uppercase.

  • array_diff_key(array $array1, array $array2) : Compare the key names of two or more arrays and return those key-value pairs in the first array that are not in other arrays.

By first using array_change_key_case() to unify the key names of the two arrays into lowercase (or uppercase), you can use array_diff_key() to achieve case-independent key name comparison.

2. Sample code

 <?php

// Original array
$array1 = [
    'UserID' => 1,
    'UserName' => 'Alice',
    'Email' => 'alice@m66.net',
];

$array2 = [
    'userid' => 2,
    'username' => 'Bob',
    'Phone' => '1234567890',
];

// Convert both array keys to lowercase
$lower1 = array_change_key_case($array1, CASE_LOWER);
$lower2 = array_change_key_case($array2, CASE_LOWER);

// Find out $array1 Those in $array2 No keys in(Ignore case)
$diffKeys = array_diff_key($lower1, $lower2);

// Output the differential key name and corresponding value
print_r($diffKeys);

?>

3. Output result

 Array
(
    [email] => alice@m66.net
)

As shown in the above example, although UserID and UserName have different key names in the two arrays, the content logic is the same. After array_change_key_case() conversion, array_diff_key() treats them as the same keys. Only the email does not appear in $array2 , so it is retained.

4. Tips

  • If you need to preserve the key name format (case) of the original array, you can first use the result of the key name conversion for comparison, and then go back to extract the corresponding key value from the original array.

  • This combination is ideal for handling dynamic data entered by users, such as field verification during form submission or API request.

5. Summary

By using array_diff_key() after the key names are uniformly cased, the case-insensitive key name comparison logic can be implemented gracefully. This method is both simple and efficient, and is a practical skill when dealing with multi-source data comparison.