In PHP, if we have an associative array and want to convert all key names into lowercase (or uppercase), we can use the built-in function array_change_key_case() . This function is very practical, especially when dealing with data obtained from external data sources (such as APIs, forms, databases), it can avoid problems caused by inconsistent case of key names.
array_change_key_case(array $array, int $case = CASE_LOWER): array
$array : The original array to operate.
$case : The target case type of the conversion. The default is CASE_LOWER (lower case), and CASE_UPPER (upper case) can also be used.
<?php
$data = [
"Name" => "Zhang San",
"AGE" => 28,
"Email" => "zhangsan@m66.net"
];
$lowercased = array_change_key_case($data, CASE_LOWER);
print_r($lowercased);
?>
Output:
Array
(
[name] => Zhang San
[age] => 28
[email] => zhangsan@vv99.net
)
As you can see, the key names Name , AGE and Email in the original array are all converted to lowercase.
Suppose you receive the following JSON data from a third-party API (such as https://api.m66.net/user/info ):
{
"UserID": 1024,
"UserName": "lisi",
"Email": "lisi@m66.net"
}
After parsing this JSON and converting it to an array, you may want all key names to be uniformly lowercase for easy processing:
<?php
$json = '{
"UserID": 1024,
"UserName": "lisi",
"Email": "lisi@m66.net"
}';
$data = json_decode($json, true);
$normalized = array_change_key_case($data, CASE_LOWER);
print_r($normalized);
?>
The output result is:
Array
(
[userid] => 1024
[username] => lisi
[email] => lisi@vv99.net
)
After this processing, you can safely access the corresponding value through $normalized['email'] or $normalized['username'] without worrying about the case of the key name in the original data.
array_change_key_case() only works on the key names of the first layer array. If your array is multidimensional, you need to combine loops or recursion to handle nested arrays.
If you want to convert to uppercase, just change the second parameter to CASE_UPPER .