In PHP, array_change_key_case() is a commonly used function that converts letters of all key names in an array to lowercase or uppercase. But when the key names of an array contain special characters (such as symbols, numbers, spaces, Chinese, etc.), what does it behave? This article will explore the details through examples.
array_change_key_case(array $array, int $case = CASE_LOWER): array
$array : The array to be processed.
$case : The constants CASE_LOWER (default) or CASE_UPPER , respectively, represent conversion to lowercase or uppercase.
$data = [
"Name" => "Alice",
"AGE" => 30,
"eMail" => "alice@m66.net"
];
$result = array_change_key_case($data, CASE_LOWER);
print_r($result);
Output:
Array
(
[name] => Alice
[age] => 30
[email] => alice@vv99.net
)
As you can see, all letter-type key names are converted to lowercase.
$data = [
"User-Name" => "Bob",
"AGE!" => 25,
"address" => "Beijing",
"Phone Number" => "1234567890",
"123KEY" => "value",
];
$result = array_change_key_case($data, CASE_UPPER);
print_r($result);
The output result is as follows:
Array
(
[USER-NAME] => Bob
[AGE!] => 25
[address] => Beijing
[PHONE NUMBER] => 1234567890
[123KEY] => value
)
Key names containing special characters (such as - , ! , spaces) : only convert the English letter parts in it, and other characters remain as they are.
Non-letter key names (such as Chinese and numerals) : will not be changed and will remain as it is.
Number keys : array_change_key_case() only processes string key names, and the number keys are not affected at all.
Let me give you another example:
$data = [
"name" => "Xiao Ming",
42 => "Number keys",
"HELLO_world!" => "test"
];
print_r(array_change_key_case($data, CASE_LOWER));
Output:
Array
(
[name] => Xiao Ming
[42] => Number keys
[hello_world!] => test
)
The scope of action of array_change_key_case() only includes key names of string type, and will only affect the case of English letters in the key names. Other characters (including special symbols, spaces, Chinese, and numbers) will not be modified. This is especially important when dealing with arrays with special format key names to avoid misoperations or key name conflicts.
When processing key names, it is important to clarify which keys may contain special characters, especially arrays generated from external APIs or user input.
If you need to completely customize the rules to process key names (such as replacing only partial characters), you can use array_map() or traverse the array to customize the processing logic.
I hope this article can help you understand the behavior and usage precautions of array_change_key_case() more clearly! If you need to further learn PHP array processing skills, please follow us for more tutorials.