PHP array_change_key_case() function


The array_change_key_case() function in PHP is used to change the case of all the keys in an associative array. This function is particularly useful when you want to normalize key case (e.g., converting all keys to lowercase or uppercase) for consistent access or comparison.

Syntax:

array_change_key_case(array $array, int $case = CASE_LOWER): array

Parameters:

  • $array: The input array whose keys you want to change.
  • $case: (Optional) The case to which you want to change the keys. This can be one of the following:
    • CASE_UPPER: Converts all keys to uppercase.
    • CASE_LOWER: Converts all keys to lowercase (default).

Return Value:

  • The function returns a new array with the keys changed to the specified case. The values remain unchanged. If the input is not an array, it returns NULL.

Example 1: Changing Keys to Lowercase

<?php $array = array( "Name" => "Alice", "AGE" => 25, "City" => "New York" ); // Change keys to lowercase $new_array = array_change_key_case($array, CASE_LOWER); print_r($new_array); ?>

Output:

Array ( [name] => Alice [age] => 25 [city] => New York )

In this example, all keys in the original array are converted to lowercase.

Example 2: Changing Keys to Uppercase

<?php $array = array( "name" => "Bob", "age" => 30, "city" => "Los Angeles" ); // Change keys to uppercase $new_array = array_change_key_case($array, CASE_UPPER); print_r($new_array); ?>

Output:

Array ( [NAME] => Bob [AGE] => 30 [CITY] => Los Angeles )

In this example, all keys in the original array are converted to uppercase.

Example 3: Handling Numeric Keys

If the array contains numeric keys, those keys will not be changed.

<?php $array = array( "Name" => "Charlie", 1 => "First", "AGE" => 28 ); // Change keys to lowercase $new_array = array_change_key_case($array, CASE_LOWER); print_r($new_array); ?>

Output:

Array ( [name] => Charlie [1] => First [age] => 28 )

In this case, the numeric key 1 remains unchanged.

Example 4: Non-Array Input

If the input provided is not an array, the function will return NULL.

<?php $not_an_array = "Hello, World!"; $result = array_change_key_case($not_an_array); var_dump($result); ?>

Output:

NULL

Practical Usage:

  • The array_change_key_case() function is particularly useful in situations where you are dealing with data from different sources that may use inconsistent key casing.
  • Normalizing key case helps avoid errors related to key mismatches when accessing or manipulating array data.

Summary:

  • array_change_key_case($array, $case) changes the case of all keys in an associative array to either lowercase or uppercase.
  • The function returns a new array with the modified keys while leaving the values unchanged.
  • It helps in maintaining consistency when working with associative arrays, especially when combining data from various sources.