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.
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.
If you want to capitalize the key names of the array, you just need to pass the CASE_UPPER constant as the second parameter.
<?php
$data = [
'name' => 'Xiao Ming',
'age' => 25,
'city' => 'Beijing'
];
$upperKeysArray = array_change_key_case($data, CASE_UPPER);
print_r($upperKeysArray);
Array
(
[NAME] => Xiao Ming
[AGE] => 25
[CITY] => Beijing
)
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);
Array
(
[NAME] => Zhang San
[AGE] => 30
[EMAIL] => zhangsan@vv99.net
)
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.
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!