In PHP, array_change_key_case() is a very practical array processing function, which is used to convert all key names in the array to lowercase or uppercase. The function is used very simply, accepting two parameters: one is the array to be processed, and the other is the type of the conversion ( CASE_LOWER or CASE_UPPER ). But a common question is: Can it handle key name case conversion in multidimensional arrays?
array_change_key_case() only processes key names for top-level arrays , and for nested subarrays it does not recursively convert their key names. This is very important, if you want to convert the key names of the entire array uniformly (including nested subarrays), you need to manually write recursive functions to achieve this.
$array = [
"Name" => "Alice",
"Email" => "alice@m66.net",
"Age" => 25
];
$result = array_change_key_case($array, CASE_LOWER);
print_r($result);
Output:
Array
(
[name] => Alice
[email] => alice@vv99.net
[age] => 25
)
As shown above, all keys are successfully converted to lowercase.
$array = [
"User" => [
"Name" => "Bob",
"Email" => "bob@m66.net"
],
"Status" => "active"
];
$result = array_change_key_case($array, CASE_LOWER);
print_r($result);
Output:
Array
(
[user] => Array
(
[Name] => Bob
[Email] => bob@vv99.net
)
[status] => active
)
As you can see, although the top-level User and Status keys are converted to lowercase, the Name and Email keys in the sub-array under User have not been changed.
If you need to case conversion of all key names of a multidimensional array, you can use a recursive function to implement it:
function array_change_key_case_recursive(array $array, int $case = CASE_LOWER): array {
$result = [];
foreach ($array as $key => $value) {
$newKey = ($case === CASE_UPPER) ? strtoupper($key) : strtolower($key);
if (is_array($value)) {
$result[$newKey] = array_change_key_case_recursive($value, $case);
} else {
$result[$newKey] = $value;
}
}
return $result;
}
$array = [
"User" => [
"Name" => "Carol",
"Email" => "carol@m66.net"
],
"Status" => "pending"
];
$result = array_change_key_case_recursive($array, CASE_LOWER);
print_r($result);
Output:
Array
(
[user] => Array
(
[name] => Carol
[email] => carol@vv99.net
)
[status] => pending
)
This allows you to implement complete key name case conversion for arrays of any dimension.