php.array_change_key_case()
In PHP, an array is a type of data structure that can hold multiple values or elements under a single variable name. These values can be of any data type such as string, integer, float, or even another array. Each value in an array is identified by a unique index or key, which can be a number or a string.
We can create an array in PHP using various methods and techniques such as the array()
function, square bracket []
notation and more. Check the tutorial below to learn more.
https://www.geekbits.io/php-array-function/
In this tutorial, we will learn how we can convert all the keys of an input array to uppercase or lowercase by using the array_change_key_case()
function.
Function Syntax
The following shows the definition for the array_change_key_case()
method.
array_change_key_case(array $array, int $case = CASE_LOWER): array
Function Parameters
The function accepts two main parameters:
array
- this refers to the input array on which the function will operate.case
- Defines the casing to which the key is converted. Accepted values areCASE_UPPER
- Convert to UppercaseCASE_LOWER
- Convert to Lowercase.
Function Return Value
The function returns an array with all the keys converted to lower case or uppercase. If the input value is not a valid array, the function will return null
.
Examples
Let us look at some basic examples of the function usage.
Example 1
The following example demonstrates how to use the function to convert all the keys of an input array to uppercase.
$databases = array(
"mysql" => 3306,
"postgresql" => 5432,
"redis" => 6379,
"sql server" => 1433
);
$databases_uppercase = array_change_key_case($databases, CASE_UPPER);
print_r($databases_uppercase);
In this case, we use the array_change_key_case()
method to convert the keys of the array to uppercase, and store the result in a new array called $databases_uppercase
.
Resulting output:
Array
(
[MYSQL] => 3306
[POSTGRESQL] => 5432
[REDIS] => 6379
[SQL SERVER] => 1433
)
Example 3
Similarly, we can use this function to convert the keys of an input array to lowercase. An example is as shown:
$databases = array(
"MYSQL" => 3306,
"POSTGRESQL" => 5432,
"REDIS" => 6379,
"SQL SERVER" => 1433
);
$databases_lowercase = array_change_key_case($databases, CASE_LOWER);
print_r($databases_lowercase);
The resulting output is as shown:
Array
(
[mysql] => 3306
[postgresql] => 5432
[redis] => 6379
[sql server] => 1433
)
Conclusion
In this tutorial, we learned how we can use the array_change_key_case()
method to convert the keys of an input array to either lower case or uppercase.
We hope you enjoyed this post.