Current Location: Home> Latest Articles> What happens when using array_change_key_case() ?

What happens when using array_change_key_case() ?

M66 2025-04-25

In PHP, array_change_key_case() is a very practical function to convert all key names in an array to lowercase or uppercase. But in actual development, sometimes we process the arrays where the key names are different but the content is the same, such as 'Name' and 'name' . What happens when we use array_change_key_case() ?

Function introduction

 array_change_key_case(array $array, int $case = CASE_LOWER): array

This function accepts two parameters:

  • $array : an array to be processed;

  • $case : The target case type of the conversion is CASE_LOWER (lower case), which can be changed to CASE_UPPER (upper case).

The return value is a new array whose key name has been converted, and the original array will not be modified.

Behavior when key names conflict

If there are multiple keys in the original array with different key names but the same content, for example:

 $array = [
    "Name" => "Alice",
    "name" => "Bob"
];

When we execute:

 $result = array_change_key_case($array, CASE_LOWER);
print_r($result);

The output will be:

 Array
(
    [name] => Bob
)

As you can see, "Name" and "name" become "name" after converting to lowercase. At this time, the subsequent key value will overwrite the previous value, so the final thing that is retained is "name" => "Bob" .

In other words, when key names conflict, the next key value overwrites the previous one .

Application scenario reminder

This behavior is especially important when you process mergers of data from different sources. For example:

 $userData = [
    "Email" => "alice@m66.net",
    "email" => "duplicate@m66.net"
];

$cleanedData = array_change_key_case($userData, CASE_LOWER);
print_r($cleanedData);

The result will be:

 Array
(
    [email] => duplicate@vv99.net
)

This can cause data to be overwritten unintentionally, so if you are worried about this, it is recommended to check for key name conflicts before conversion, or use a more nuanced approach (such as traversal and manual detection).

Summarize

Use array_change_key_case() to unify the upper and lower case of key names and improve code consistency. But if there are key names in the array with different case but same content, they will conflict after conversion, and the subsequent values ​​will overwrite the previous values . This type of situation should be handled with caution when using this function, especially in data structures involving data integration or user input.