Change the case of all keys in an array with array_change_key_case() function in php

This post is about a function that will help you change the case of all keys in an array. Suppose you have a array in php declared as follows:

Now we can simply use the array_change_key_case function to change the case of array keys. Here are the examples

You get the output which has all keys changed to lower case:

Array ( [a] => apple [b] => bat [c] => cat )

Now to change all keys to upper case, you can use the CASE_UPPER constant instead of CASE_LOWER when calling the array_change_key_case function.

Syntax

array_change_key_case(array,case);

array: the array who keys are to be changed.

case: (optional) either CASE_LOWER or CASE_UPPER

 

return value: the array with changed keys (returns false if array is invalid)

What if array contains same keys with different cases

If the array contains same keys with different cases, the last one is preserved. This example demonstrates it.

Output

Array ( [john] => 30 [mike] => 22 )

Notice that [john]=>25 was replaced by [john]=>30.

 

Note:

  • If you didn’t specify any case, it defaults to CASE LOWER
  • This function is supported from PHP 4.2 and above

Leave a Reply

Your email address will not be published. Required fields are marked *