The array_change_key_case()
function in PHP is used to change the case of all keys in an array. The function accepts an array as its first parameter and an optional second argument specifying the case to which the keys should be changed.
What is the syntax of the array_change_key_case function in PHP?
array_change_key_case(array $array [, int $case = CASE_LOWER]) : array
Parameter | Details |
array | Convert the keys of this array into parameters. |
case | There are two cases: – CASE UPPER – CASE LOWER |
Here are a few examples of how to use the array_change_key_case()
function:
Example 1:
$fruits = array("Apple" => "red", "Banana" => "yellow", "Cherry" => "red");
$fruits = array_change_key_case($fruits, CASE_UPPER);
print_r($fruits);
In this example, we’ll make an associative array of fruits and colors. The array change key case() method is then used to change the case of all keys to uppercase. The keys in the resultant array will be “APPLE”, “BANANA”, and “CHERRY”.
Example 2:
$numbers = array(1 => "one", 2 => "two", 3 => "three");
$numbers = array_change_key_case($numbers);
print_r($numbers);
In this example, we will build an associative array containing integers and words. Then, without the second parameter, we call the array change key case() method, which converts all keys to lowercase by default. The keys in the resultant array will be “1”, “2”, and “3”.
Example 3:
$employee = array("Name" => "John Doe", "Age" => 30, "Salary" => 5000);
$employee = array_change_key_case($employee, CASE_UPPER);
print_r($employee);
In this example, we’ll make an associative array containing employee information. The array change key case() method is then used to change the case of all keys to uppercase. The keys in the resultant array will be “NAME”, “AGE”, and “SALARY”.
It’s worth noting that the array change key case() method returns a new array with the updated keys, rather than modifying the existing array.