Fueling Your Coding Mojo

Buckle up, fellow PHP enthusiast! We're loading up the rocket fuel for your coding adventures...

Popular Searches:
1012
Q:

PHP array_change_key_case() function (with example)

Hey folks,

I am fairly new to PHP and I have come across a function called `array_change_key_case()` but I'm a bit confused about how it works. I was hoping someone could provide me with a simple explanation and maybe an example to help me understand it better.

Thanks in advance for your help!

All Replies

jordon.feil

Hey there,

I've actually used `array_change_key_case()` in one of my PHP projects, so I can definitely help you with that! This function is used to change the case of the keys in an array. It comes in handy when you need to manipulate the keys to be either all uppercase or all lowercase.

For example, let's say you have an array with mixed case keys like this:

php
$myArray = array(
"Name" => "John",
"Age" => 25,
"Email" => "john@example.com"
);


Now, if you want to convert all the keys to lowercase, you can simply use `array_change_key_case()` like this:
php
$newArray = array_change_key_case($myArray, CASE_LOWER);


After applying this function, the `$newArray` would look like:
php
Array
(
[name] => John
[age] => 25
[email] => john@example.com
)


Similarly, if you want to convert the keys to uppercase, you would use `array_change_key_case()` like this:
php
$newArray = array_change_key_case($myArray, CASE_UPPER);


Then, the `$newArray` would look like:
php
Array
(
[NAME] => John
[AGE] => 25
[EMAIL] => john@example.com
)


I hope this clears things up for you. Let me know if you have any more questions!

isobel32

Hey everyone,

I've used `array_change_key_case()` quite a bit in my PHP projects, and it's a handy function to have in your arsenal. This function allows you to change the case of the array keys, either making them all uppercase or all lowercase.

Let me share an example from a recent project. I had an array with mixed case keys like this:

php
$fruits = array(
"AppLe" => "Red",
"bAnaNa" => "Yellow",
"oRaNGe" => "Orange"
);


To standardize the case of the keys, I needed them all to be lowercase. So, I used `array_change_key_case()` like this:
php
$lowercaseFruits = array_change_key_case($fruits, CASE_LOWER);


After applying this function, the resulting array `$lowercaseFruits` looked like this:
php
Array
(
[apple] => Red
[banana] => Yellow
[orange] => Orange
)


This simple modification was particularly useful when I needed to perform case-insensitive key lookups or comparisons.

It's worthwhile to note that the function is not limited to converting to lowercase only; you can also use `CASE_UPPER` to convert the keys to uppercase.

I hope this example helps you understand how `array_change_key_case()` works. Let me know if you have any further queries!

New to LearnPHP.org Community?

Join the community