Current Location: Home> Latest Articles> How to convert array keys to uppercase using array_change_key_case()?

How to convert array keys to uppercase using array_change_key_case()?

M66 2025-04-25

In PHP, array_change_key_case() is a very practical function to change the case of all key names in an array. This function is particularly suitable for handling inconsistent key name formats, such as if you get an array from a database or interface and want to unify the format to facilitate subsequent processing.

1. Function syntax

 array_change_key_case(array $array, int $case = CASE_LOWER): array
  • $array : The original array to be processed.

  • $case : Specifies the type of conversion. Can be:

    • CASE_LOWER (default) converts the key name to lower case.

    • CASE_UPPER converts the key name to uppercase.

2. Turn the array key name into capital

If you want to capitalize the key names of the array, you just need to pass the CASE_UPPER constant as the second parameter.

Sample code:

 <?php

$data = [
    'name' => 'Xiao Ming',
    'age' => 25,
    'city' => 'Beijing'
];

$upperKeysArray = array_change_key_case($data, CASE_UPPER);

print_r($upperKeysArray);

Output result:

 Array
(
    [NAME] => Xiao Ming
    [AGE] => 25
    [CITY] => Beijing
)

3. Examples of practical application scenarios

Suppose you get an array of user information from the interface https://api.m66.net/user/info , but the key names are not case-uniform, you can use array_change_key_case() to convert it to uppercase uniformly:

 <?php

// Data returned by simulation interface
$userInfo = [
    'Name' => 'Zhang San',
    'Age' => 30,
    'Email' => 'zhangsan@m66.net'
];

// Convert all key names to capitalization
$userInfoUpper = array_change_key_case($userInfo, CASE_UPPER);

print_r($userInfoUpper);

Output result:

 Array
(
    [NAME] => Zhang San
    [AGE] => 30
    [EMAIL] => zhangsan@vv99.net
)

4. Things to note

  • This function does not process subarrays recursively , and only changes the key names of the outermost array.

  • The original array will not be modified, and a new array is returned.

5. Summary

Using array_change_key_case() is a concise and efficient method that can help us quickly unify the format of array key names, especially suitable for use when it is necessary to deal with irregular data. The conversion is easily completed with just one parameter (or two parameters specify capitalization).

If you want to process key names in nested arrays at the same time, you can also customize the recursive version to implement it, which requires writing more logic. In a simple scenario, using the built-in array_change_key_case() is already very useful!