php array change key case
php: Array keys case *insensitive* lookup?
I don’t create the array, an thus can not control it’s keys
12 Answers 12
You can’t do this without either a linear search or altering the original array. The most efficient approach will be to use strtolower on keys when you insert AND when you lookup values.
If it’s important to you to preserve the original case of the key, you could store it as a additional value for that key, e.g.
As you updated the question to suggest this wouldn’t be possible for you, how about you create an array providing a mapping between lowercased and case-sensitive versions?
Now you can use this to obtain the case-sensitive key from a lowercased one
This avoids the need to create a full copy of the array with a lower-cased key, which is really the only other way to go about this.
If making a full copy of the array isn’t a concern, then you can use array_change_key_case to create a copy with lower cased keys.
I know this is an older question but the most elegant way to handle this problem is to use:
Alternatively you can use:
You could use ArrayAccess interface to create a class that works with array syntax.
Example
Class
I combined Paul Dixon’s idea of creating a mapping for the keys and Kendall Hopkins’ idea of using the ArrayAccess interface for retaining the familiar way of accessing a PHP array.
The result is a class that avoids copying the initial array and allows transparent case-insensitive access, while internally preserving the keys’ case. Limitation: If case-insensitively equal keys (e.g. ‘Foo’ and ‘foo’) are contained in the initial array or are added dynamically, then latter entries will overwrite previous ones (rendering these inaccessible).
The CaseInsensitiveKeysArray class
PHP array_change_key_case() Function
Definition and Usage
The array_change_key_case() function changes the case of all keys of the passed array and returns an array with all keys either in lower case or upper case based on the option passed.
By default this function returns lower cased keys.
Syntax
Parameters
This is the array for which you want to change the case of all the keys.
This will take constant value either CASE_UPPER or CASE_LOWER. If you do not pass this value then function will change the keys to lower case.
Return Values
PHP array_change_key_case() function returns an array with its keys either in lower case or upper case, or FALSE if passed input is not a valid PHP array.
PHP Version
This function was first introduced in PHP Version 4.2.0.
Example
Try out following example in which we are converting all the keys into upper case −
This will produce following result −
Example
Following example converts all the keys into lower case −
This will produce following result −
Example
Let’s check how default case will work if we don’t pass second option in the function −
This will produce following result −
Example
Following example returns FALSE and raises a warning because we are trying to pass a simple PHP string instead of a PHP array −
This does not produce any output, rather it will display following warning, and if you will check function return value then it will be FALSE −
How to convert all keys in a multi-dimenional array to snake_case?
I am trying to convert the keys of a multi-dimensional array from CamelCase to snake_case, with the added complication that some keys have an exclamation mark that I’d like removed.
I would like to convert to:
My real-life array is huge and goes many levels deep. Any help with how to approach this is much appreciated!
7 Answers 7
This is the modified function I have used, taken from soulmerge’s response:
Here’s a more generalized version of Aaron’s. This way you can just plug the function you want to be operated on for all keys. I assumed a static class.
Although this may not be an exact answer to the question, but I wanted to post it here for people who are searching for elegant solution for changing key case in multidimensional PHP arrays. You can also adapt it for changing array keys in general. Just call a different function instead of array_change_key_case_recursive
You can run a foreach on the arrays keys, this way you’ll rename the keys in-place:
Create a function like:
and call this like:
for working example see this
I’d say you would have to write a function to copy the array (one level) and have that function call itself if any of the values is an array (a recursive function).
What exactly do you need any specific help with?
3 Ways to Change Array Key without Changing the Order in PHP
DISCLOSURE: This article may contain affiliate links and any sales made through such links will reward us a small commission, at no extra cost for you. Read more about Affiliate Disclosure here.
You can change array key too easily but doing it without changing the order in PHP is quite tricky. Simply assigning the value to a new key and deleting old one doesn’t change the position of the new key at the place of old in the array.
So in this article, I have explained 3 ways to let you change array key while maintaining the key order and last one of them can be used with a multidimensional array as well. But before that, if you just need to rename a key without preserving the order, the two lines code does the job:
1. Change Array Key using JSON encode/decode
It’s short but be careful while using it. Use only to change key when you’re sure that your array doesn’t contain value exactly same as old key plus a colon. Otherwise, the value or object value will also get replaced.
2. Replace key & Maintain Order using Array Functions in PHP
The function replace_key() first checks if old key exists in the array? If yes then creates an Indexed Array of keys from source array and change old key with new using PHP array_search() function.
Finally, array_combine() function returns a new array with key changed, taking keys from the created indexed array and values from source array. The non-existence of old key just simply returns the array without any change.
3. Change Array Key without Changing the Order (Multidimensional Array Capable)
This solution is quite elegant and can work with multidimensional array too with help of classic PHP loop and recursive function call. Let’s see how are we doing this change.
Here we need to pass two arrays in the function call (Line #20). The first parameter is the array which needs to change keys and another is an array containing indexes as old keys and values as new keys. Upon execution, the function will change all the keys in the first array which are present in the second array too and their respective values will be new keys.
The recursive calling within function ensures changing keys up to the deepest branch of the array. The function recursive_change_key() here is provided along with the example to understand better.
Don’t forget to read our extensive list of 38 PHP related tutorials yet.
So here you got 3 ways to change array key without changing the order of array in PHP. And the last one works with a multidimensional array as well. All you need is just to provide correct set of “old key, new key” pairs for changing purpose.
You Might Interested In
13 COMMENTS
Edit: ( in the unit test \TGHelpers_Array::renameKeyKeepingOrder is where i put the function replace_key() )
It’s nice that you improved the function to consist of numeric/floating keys.
A little bit more complicated, but can do associative arrays with out having to create a new array: http://php.net/manual/en/function.array-walk.php#122991
That’s good. Yet that piece of code requires more processing time as well as passing many parameters which isn’t less than memory occupied by the temporary array created here.
That’s good. Yet that piece of code requires more processing time as well as passing many parameters which isn’t less than memory occupied by the temporary array created here.
I didn’t say it was a better way, just another way. =P
Haha lol. I admit you’re smarter than me.
I wouldn’t say I’m “smart”. Just more determine to do crazy things.
That’s nice habit until things don’t get complicated :-D. Have a good time ahead!
Serialization, regular expression and JSON string always have performance issue. Rest all are around near except the benchArrayKeys.
I think there is a typo
Line 6 : it rather be
because it’s recursive 😀
Leave a Reply Cancel reply
GET IN TOUCH
WE’RE AVAILABLE
AS Tech Solutions is an Android Apps and Web Design & Development company, offering the following services:
FACEBOOK FANS
Hey buddy 🙋♂️ SUP? I’m Amit, a passionate tech blogger and Android & web application developer. Check our services and enjoy these hand-picked articles as well:
array_change_key_case
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
array_change_key_case — Меняет регистр всех ключей в массиве
Описание
Список параметров
Возвращаемые значения
Ошибки
Примеры
Пример #1 Пример использования array_change_key_case()
Результат выполнения данного примера:
Примечания
Если массив содержит индексы, которые станут одноименными после применения данной функции (например, «keY» и «kEY«), значение последнего одноименного индекса перекроет другие совпадающие значения из этого массива.
Коментарии
I just changed the code a little bit so you havent got a code that repeats itself.
/*
Array
(
[A] => Hello
[B] => World
[a] => how are you?
)
Array
(
[A] => Array
(
[0] => Hello
[1] => how are you?
)
multibyte and multi-dimensional-array support, have fun!
//for more speed define the runtime created functions in the global namespace
//first-char-to-uppercase
case 20 :
$function = ‘ucfirst’ ;
break;
Below is a recursive version of this function.
Same as array_change_key_case only with the values. This should really be part of PHP!
Simple function to change multidimensional array’s all values to uppercase. If you would like to change to lowercase then change «mb_strtoupper» to «mb_strtolower». It works perfect for me 😉
Script to change case of sub-arrays keys:
Use this to capitalize first letter of all array keys:
?>
Result:
Array ( [MoreFoo] => Array ( [More] => foo ) [Foo] => bar )
Here is the most compact way to lower case keys in a multidimensional array
Recursive LowerCase First Letter in array key
$input = [‘test1’=>1, ‘Test2’ => 2, ‘TeSt3’ => 3];
print_r(convert_to_key_case($input, ‘uppercase’));
print_r(convert_to_key_case($input, ‘lowercase’));
Array (
[test1] => 1
[test2] => 2
[test3] => 3
)