In PHP, array_change_key_case() is a very practical function. Its function is to uniformly convert the upper and lowercase letters of all key names in the array, and the default is to convert them to lowercase letters. This function is often used to ensure consistency in the key name format when processing data from different sources.
So the question is: Will using array_change_key_case() modify the original array?
array_change_key_case() is a non-destructive function , which means it does not directly modify the original array passed in, but returns a new array with the key name converted after the upper and lowercase and lowercase character. If you want to retain the modified result, you must assign it to a variable.
<?php
$original = [
"Name" => "Alice",
"AGE" => 25,
"Email" => "alice@m66.net"
];
// use array_change_key_case The original array will not be modified
$changed = array_change_key_case($original, CASE_LOWER);
print_r($original);
echo "--------\n";
print_r($changed);
?>
Output result:
Array
(
[Name] => Alice
[AGE] => 25
[Email] => alice@vv99.net
)
--------
Array
(
[name] => Alice
[age] => 25
[email] => alice@vv99.net
)
As you can see, the $original array remains unchanged, while $changed is a new array, and the key name has been converted to lowercase.
array_change_key_case(array $array, int $case = CASE_LOWER): array
$array : The input array to be processed.
$case : optional, specify the conversion type:
CASE_LOWER (default): Convert to lowercase.
CASE_UPPER : Convert to uppercase.
This function only works on one-dimensional arrays and does not recursively process the key names of multidimensional arrays.
If there are duplications of the converted key names, the value will be overwritten. For example, ["a" => 1, "A" => 2] will become ["a" => 2] after converting to lower case.
array_change_key_case() is a convenient tool in PHP for handling the case of array key names. It does not modify the original array, but returns a new array. Remember: be sure to catch the return value when using it, otherwise the conversion will make no sense.
I hope this article can help you understand the usage and characteristics of array_change_key_case() more clearly!