The basic syntax for the array_change_key_case in PHP:

<?php
   $array = array(
      'item1' => 'Item 1',
      'item2' => 'Item 2'
   );
   array_change_key_case( $array, CASE_UPPER );
?>

The array_change_key_case is a built-in PHP function used to convert the array keys into upper case or lower case and that can be done by using the flag argument.

PHP array_change_key_case

Moreover, the basic expression of the array_change_key_case callback would be like the below.

array_change_key_case( ARRAY, FLAG );

The function arguments.

  • Required array with keys.
  • Optional flag name.
    • CASE_UPPER to change the array keys to upper case.
    • CASE_LOWER to change the array keys to lower case.

The default flag name for the array_change_key_case function is lower case.

The array_change_key_case doesn’t matter if the array type is indexed array or associative array. It only searching about the keys if it has letters so it will change it, otherwise it will return the same array without any issue.

PHP array_change_key_case() Examples

The array_change_key_case couldn’t able to reach the keys of the nested arrays.

<?php

   $users = array(
      array(
        "nAme" => "Ahmed",
        "agE"  => "25 years old" 
      ),
      array(
        "namE" => "Sadek",
        "aGE"  => "35 years old" 
      )
   );

   $convert_keys = array_change_key_case( $users); // will do nothing
   print_r( $convert_keys );

?>

In this example the array will not be affected until you doing a loop for the nested arrays like the below.

<?php

   $users = array(
      array(
        "nAme" => "Ahmed",
        "agE"  => "25 years old" 
      ),
      array(
        "namE" => "Sadek",
        "aGE"  => "35 years old" 
      )
   );
   
   foreach($users as $key => $value ) {
     $users[$key] = array_change_key_case( $value); 
   }
    
   print_r( $users );

?>

This will print the following result.

Array
(
    [0] => Array
        (
            [name] => Ahmed
            [age] => 25 years old
        )

    [1] => Array
        (
            [name] => Sadek
            [age] => 35 years old
        )

)

If you need to convert the keys case to upper case you have to use this flag CASE_UPPER in the second argument.

Note: the usage of this function, to convert all key letters in the direct array. So if the array has another array that will not work until you used the loop to reach it.

Wrapping Up

The array_change_key_case used to convert the case of array keys to upper case or lower case. The default flag is CASE_LOWER. It accepts two arguments $array and Flag.

For more details visit the PHP manual.