PHP array_change_key_case Function
last modified March 13, 2025
The PHP array_change_key_case
function changes the case of all
keys in an array. It can convert keys to uppercase or lowercase.
Basic Definition
The array_change_key_case
function returns an array with all
keys converted to the specified case. It works with both string and numeric
keys.
Syntax: array_change_key_case(array $array, int $case = CASE_LOWER): array
.
The $case
parameter can be either CASE_LOWER
or
CASE_UPPER
.
Basic array_change_key_case Example
This example demonstrates converting all array keys to lowercase.
<?php $user = [ 'FirstName' => 'John', 'LastName' => 'Doe', 'Age' => 30 ]; $lowerKeys = array_change_key_case($user); print_r($lowerKeys);
The output will show all keys converted to lowercase. Numeric keys remain unchanged as they're not affected by case conversion.
Converting to Uppercase
This example shows how to convert all keys to uppercase using the function.
<?php $config = [ 'db_host' => 'localhost', 'db_user' => 'admin', 'db_pass' => 'secret' ]; $upperKeys = array_change_key_case($config, CASE_UPPER); print_r($upperKeys);
The resulting array will have all keys in uppercase. This is useful when you need consistent key cases for case-sensitive operations.
Mixed Key Types
The function handles arrays with mixed key types (string and numeric).
<?php $mixed = [ 'Name' => 'Alice', 0 => 'Zero', 'Age' => 25, 1 => 'One' ]; $lowerMixed = array_change_key_case($mixed); print_r($lowerMixed);
Only string keys are converted to lowercase. Numeric keys remain unchanged in the output array, maintaining their original values and positions.
Duplicate Key Handling
When case conversion creates duplicate keys, later values overwrite earlier ones.
<?php $data = [ 'USERNAME' => 'admin', 'username' => 'guest', 'Password' => '12345' ]; $uniformKeys = array_change_key_case($data); print_r($uniformKeys);
Both 'USERNAME' and 'username' become 'username' after conversion. The last occurrence ('guest') overwrites the first value ('admin') in the result.
Multidimensional Arrays
The function only changes keys at the top level of the array structure.
<?php $company = [ 'CompanyName' => 'ACME', 'Departments' => [ 'Sales' => ['John', 'Jane'], 'IT' => ['Mike', 'Sarah'] ] ]; $lowerCompany = array_change_key_case($company); print_r($lowerCompany);
Only the top-level keys ('CompanyName' and 'Departments') are converted. Nested array keys remain unchanged, preserving their original case.
Best Practices
- Consistency: Use consistent key cases throughout your code.
- Case Sensitivity: Be aware of case-sensitive operations.
- Data Integrity: Check for potential key collisions.
- Performance: Consider impact on large arrays.
Source
PHP array_change_key_case Documentation
This tutorial covered the PHP array_change_key_case
function with
practical examples showing its usage for array key case conversion.
Author
List all PHP Array Functions.