In PHP array operations, the case of key names sometimes affects the processing results of the data. In order to unify the format of array key names, PHP provides a very practical function: array_change_key_case() . This function can convert all key names in the array to uppercase or lowercase, especially suitable for data cleaning, standardization and other scenarios.
array_change_key_case(array $array, int $case = CASE_LOWER): array
$array : Required. The input array to be processed.
$case : optional. The case type of the conversion. The default is CASE_LOWER (convert to lower case), or CASE_UPPER (convert to upper case).
Here is a simple example showing how to convert array key names to lowercase and uppercase using array_change_key_case() .
<?php
$data = [
"Name" => "Alice",
"EMAIL" => "alice@m66.net",
"Age" => 25
];
// Convert to lowercase key name
$lowercaseKeys = array_change_key_case($data, CASE_LOWER);
print_r($lowercaseKeys);
/* Output:
Array
(
[name] => Alice
[email] => alice@vv99.net
[age] => 25
)
*/
// Convert to capital key name
$uppercaseKeys = array_change_key_case($data, CASE_UPPER);
print_r($uppercaseKeys);
/* Output:
Array
(
[NAME] => Alice
[EMAIL] => alice@vv99.net
[AGE] => 25
)
*/
?>
The key value remains unchanged : array_change_key_case() only changes the case of the key name and will not affect the value of the array.
Key name conflict : If a duplicate key name is generated after the conversion (for example, "Email" and "EMAIL" exist), the next key will overwrite the previous one.
Applicable only to string key names : numeric key names will not be affected.
Suppose you get user data from an API, and the key names in the returned result are inconsistent format:
$response = [
"User_ID" => 101,
"user_name" => "Bob",
"EMAIL" => "bob@m66.net"
];
For easy processing, you may need to have a unified key name in lowercase:
$cleanedResponse = array_change_key_case($response, CASE_LOWER);
Unified key names can reduce the possibility of errors when processing data, especially when using functions such as array_key_exists() and isset() .