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:
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
Output:
In this example, all keys in the original array are converted to lowercase.
Example 2: Changing Keys to Uppercase
Output:
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.
Output:
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
.
Output:
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.