Current Location: Home> Latest Articles> array_change_key_case() combined with array_flip()

array_change_key_case() combined with array_flip()

M66 2025-04-25

In PHP, array_change_key_case() is a very practical array function that uniformly converts all key names in an array. This function can simplify the problem caused by case inconsistency when processing user input or interface data.

grammar

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

Parameter description:

  • $array : Required, input array to be processed.

  • $case : optional, the default is CASE_LOWER , indicating conversion to lower case. You can also use CASE_UPPER to convert to uppercase.

Return value

This function returns a new array whose key name has been converted in case, and the original array remains unchanged.

Example 1: Convert to lowercase key names by default

 $data = [
    "Name" => "Alice",
    "AGE" => 25,
    "City" => "Shanghai"
];

$result = array_change_key_case($data);

print_r($result);

Output:

 Array
(
    [name] => Alice
    [age] => 25
    [city] => Shanghai
)

Example 2: Convert to capital key name

 $data = [
    "Name" => "Bob",
    "gender" => "Male",
    "country" => "China"
];

$result = array_change_key_case($data, CASE_UPPER);

print_r($result);

Output:

 Array
(
    [NAME] => Bob
    [GENDER] => Male
    [COUNTRY] => China
)

Things to note

  1. If there are multiple items in the array with only different key names, key names conflicts will occur during the conversion process, and the latter will overwrite the previous one.

  2. This function does not affect the key names of the nested arrays, and only processes the outermost layer.

Example 3: Key name conflict situation

 $data = [
    "Email" => "user1@m66.net",
    "EMAIL" => "user2@m66.net"
];

$result = array_change_key_case($data, CASE_LOWER);

print_r($result);

Output:

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

As shown above, "EMAIL" overrides the value of "Email".

Application scenarios

  • Eliminate case differences when processing array data from different sources uniformly.

  • Improve accuracy and consistency when comparing or searching array key values.

  • Used to build case-insensitive configuration read functionality.

Tips

Combining array_change_key_case() and array_map() can implement more complex data preprocessing logic, such as uniformly processing form data submitted by users.