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.
array_change_key_case(array $array, int $case = CASE_LOWER): array
$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.
This function returns a new array whose key name has been converted in case, and the original array remains unchanged.
$data = [
"Name" => "Alice",
"AGE" => 25,
"City" => "Shanghai"
];
$result = array_change_key_case($data);
print_r($result);
Array
(
[name] => Alice
[age] => 25
[city] => Shanghai
)
$data = [
"Name" => "Bob",
"gender" => "Male",
"country" => "China"
];
$result = array_change_key_case($data, CASE_UPPER);
print_r($result);
Array
(
[NAME] => Bob
[GENDER] => Male
[COUNTRY] => China
)
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.
This function does not affect the key names of the nested arrays, and only processes the outermost layer.
$data = [
"Email" => "user1@m66.net",
"EMAIL" => "user2@m66.net"
];
$result = array_change_key_case($data, CASE_LOWER);
print_r($result);
Array
(
[email] => user2@vv99.net
)
As shown above, "EMAIL" overrides the value of "Email".
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.
Combining array_change_key_case() and array_map() can implement more complex data preprocessing logic, such as uniformly processing form data submitted by users.